feat: adopt shared internal SSO sessions and add no-sso launch mode
This commit is contained in:
1 parent
c209f1effc
commit
c02bf755f2
51 files changed
+2131
-362
No files matched your search
@@ -2,3 +2,11 @@
|
||||
*.sh text eol=lf
|
||||
*.ps1 text eol=lf
|
||||
*.service text eol=lf
|
||||
|
||||
# Keep frontend checkout consistent with Prettier on Windows.
|
||||
*.vue text eol=lf
|
||||
*.ts text eol=lf
|
||||
*.js text eol=lf
|
||||
*.cjs text eol=lf
|
||||
*.css text eol=lf
|
||||
*.json text eol=lf
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
[Мобильный интерфейс](docs/images/workspace-mobile.png)
|
||||
|
||||
- **SSO вместо паролей.** OIDC, роли `Master Admin` и `FS Admin`, профиль и аватар.
|
||||
- **Общая сессия SSO.** Текущий аккаунт и роли проверяются на сервере; переключение синхронизируется между приложениями.
|
||||
- **Удобное пространство.** Дерево папок, закладки, поиск, меню действий, светлая и тёмная темы, мобильная вёрстка.
|
||||
- **Мои ссылки.** Короткие адреса `/s/имя`, несколько ссылок на файл, необязательные пароль и срок действия.
|
||||
- **Предпросмотр.** Изображения, PDF, DICOM 2D, текст, Markdown, CSV, книги, аудио и видео. ZIP показывает дерево без распаковки.
|
||||
@@ -25,6 +25,8 @@ chmod +x filebrowser
|
||||
|
||||
На Windows: `filebrowser.exe init`, затем `filebrowser.exe`. Мастер настраивает хранилище и SSO без `.env`. Подробности, systemd и nginx — в [инструкции](docs/deployment.md).
|
||||
|
||||
Без SSO и пароля: `./filebrowser --no-sso` — все посетители получают административный доступ. [Как работает вход](docs/authentication.md).
|
||||
|
||||
## Сборка
|
||||
|
||||
Go 1.26+, Node.js 24+, pnpm 10.33.4.
|
||||
|
||||
@@ -122,6 +122,7 @@ var initCmd = &cobra.Command{
|
||||
c.ImageProcessors = min(2, runtime.NumCPU())
|
||||
public, _ := url.Parse(c.SSO.PublicURL)
|
||||
c.BaseURL = strings.TrimRight(public.Path, "/")
|
||||
c.SSO.RedirectURI = strings.TrimRight(c.SSO.PublicURL, "/") + "/auth/callback"
|
||||
c.DisableExec = true
|
||||
if err = os.MkdirAll(c.Root, 0750); err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestOnlyExplicitNoSSOFlagSkipsInitialSSOSetup(t *testing.T) {
|
||||
for _, enabled := range []bool{false, true} {
|
||||
dir := t.TempDir()
|
||||
config := filepath.Join(dir, "config.json")
|
||||
// A JSON setting must not enable this process-only bypass.
|
||||
if err := os.WriteFile(config, []byte(`{"no-sso":true}`), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
command := &cobra.Command{Use: "filebrowser"}
|
||||
command.Flags().String("config", config, "")
|
||||
command.Flags().String("database", filepath.Join(dir, "test.db"), "")
|
||||
command.Flags().Bool("no-sso", false, "")
|
||||
if enabled {
|
||||
command.Flags().Set("no-sso", "true")
|
||||
}
|
||||
called := false
|
||||
err := withViperAndStore(func(_ *cobra.Command, _ []string, _ *viper.Viper, _ *store) error { called = true; return nil }, storeOptions{allowsNoDatabase: true})(command, nil)
|
||||
if enabled && (err != nil || !called) {
|
||||
t.Fatalf("explicit flag blocked: %v", err)
|
||||
}
|
||||
if !enabled && (err == nil || called) {
|
||||
t.Fatal("configuration silently enabled no-sso")
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
-5
@@ -85,6 +85,7 @@ func init() {
|
||||
|
||||
// Runtime flags for the root command
|
||||
flags := rootCmd.Flags()
|
||||
flags.Bool("no-sso", false, "start without SSO or passwords; everyone with network access is an administrator")
|
||||
flags.Uint32("socketPerm", 0666, "unix socket file permissions")
|
||||
flags.String("cacheDir", "", "file cache directory (disabled if empty)")
|
||||
flags.String("redisCacheUrl", "", "redis cache URL (for multi-instance deployments), e.g. redis://user:pass@host:port")
|
||||
@@ -119,8 +120,8 @@ var rootCmd = &cobra.Command{
|
||||
manage your users and all the configurations without accessing the
|
||||
web interface.
|
||||
|
||||
Run filebrowser init for initial setup. It creates the configuration file, prepares the database and prints the SSO callback URL. Local password accounts and command execution are not supported. Runtime options can still be overridden using flags or FB_ environment variables.`,
|
||||
RunE: withViperAndStore(func(_ *cobra.Command, _ []string, v *viper.Viper, st *store) error {
|
||||
Run filebrowser init for initial setup. It creates the configuration file, prepares the database and prints the SSO callback URL. Local password accounts and command execution are not supported. Use --no-sso to start without SSO or passwords, granting administrator access to all visitors. Runtime options can still be overridden using flags or FB_ environment variables.`,
|
||||
RunE: withViperAndStore(func(cmd *cobra.Command, _ []string, v *viper.Viper, st *store) error {
|
||||
if !st.databaseExisted {
|
||||
err := quickSetup(v, st.Storage)
|
||||
if err != nil {
|
||||
@@ -156,7 +157,7 @@ Run filebrowser init for initial setup. It creates the configuration file, prepa
|
||||
}
|
||||
setupLog(server.Log)
|
||||
|
||||
log.Println("File Browser SSO edition")
|
||||
log.Println("File Browser")
|
||||
|
||||
root, err := filepath.Abs(server.Root)
|
||||
if err != nil {
|
||||
@@ -206,10 +207,20 @@ Run filebrowser init for initial setup. It creates the configuration file, prepa
|
||||
// Execution hooks and external symlinks are never enabled in this fork.
|
||||
server.EnableExec = false
|
||||
server.FollowExternalSymlinks = false
|
||||
sso, err := fbhttp.NewSSO(context.Background(), st.Storage, server, fbhttp.SSOConfig{Issuer: v.GetString("sso.issuer"), ClientID: v.GetString("sso.clientID"), ClientSecret: v.GetString("sso.clientSecret"), PublicURL: v.GetString("sso.publicURL")})
|
||||
var authentication interface {
|
||||
Wrap(http.Handler) http.Handler
|
||||
}
|
||||
noSSO, _ := cmd.Flags().GetBool("no-sso")
|
||||
if noSSO {
|
||||
authentication, err = fbhttp.NewNoSSO(st.Storage, server)
|
||||
log.Println("--no-sso: authentication disabled; all visitors have administrator access")
|
||||
} else {
|
||||
authentication, err = fbhttp.NewSSO(context.Background(), st.Storage, server, fbhttp.SSOConfig{Issuer: v.GetString("sso.issuer"), ClientID: v.GetString("sso.clientID"), ClientSecret: v.GetString("sso.clientSecret"), PublicURL: v.GetString("sso.publicURL"), RedirectURI: v.GetString("sso.redirectURI")})
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
handler, err := fbhttp.NewHandler(imageService, fileCache, uploadCache, st.Storage, server, assetsFs)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -219,7 +230,7 @@ Run filebrowser init for initial setup. It creates the configuration file, prepa
|
||||
|
||||
log.Println("Listening on", listener.Addr().String())
|
||||
srv := &http.Server{
|
||||
Handler: sso.Wrap(handler),
|
||||
Handler: authentication.Wrap(handler),
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
IdleTimeout: 90 * time.Second,
|
||||
MaxHeaderBytes: 1 << 20,
|
||||
|
||||
+2
-1
@@ -153,7 +153,8 @@ func withViperAndStore(fn func(cmd *cobra.Command, args []string, v *viper.Viper
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if cmd.Parent() == nil && cmd.Use == "filebrowser" && (v.GetString("sso.issuer") == "" || v.GetString("sso.clientID") == "" || v.GetString("sso.clientSecret") == "" || v.GetString("sso.publicURL") == "") {
|
||||
noSSO, _ := cmd.Flags().GetBool("no-sso")
|
||||
if cmd.Parent() == nil && cmd.Use == "filebrowser" && !noSSO && (v.GetString("sso.issuer") == "" || v.GetString("sso.clientID") == "" || v.GetString("sso.clientSecret") == "" || v.GetString("sso.publicURL") == "") {
|
||||
return errors.New("initial setup required: run filebrowser init")
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
# Проверка 3.2.0
|
||||
|
||||
- OIDC: PKCE S256, HTTP Basic, nonce/at_hash/RS256-проверка, повтор callback, изолированные cookies транзакций и host-only Secure/HttpOnly handle.
|
||||
- Внутренний resolve: запрос на каждую операцию без положительного кеша, строгие client_id/sub/expiry, текущие роли, отказ при ошибке провайдера/невалидном ответе без удаления cookie.
|
||||
- Два настоящих HTTP-сервера File Browser с тестовыми БД/файлами и общий имитатор SSO: Alice → Bob в двух открытых приложениях без OAuth-обмена, независимое устройство остаётся Alice, отказ Bob, сбой/восстановление SSO, общий logout и недостающий фактор.
|
||||
- Поздний ответ Alice задержан до перехода на Bob; данные Alice не возвращаются в интерфейс. Старая форма отвергается с 409. Тестируется также недоступный iframe-брокер — работает запасной опрос backend.
|
||||
- TUS: другой аккаунт или новая версия сессии не продолжает старую загрузку; очередь и запросы отменяются при смене аккаунта.
|
||||
- Без SSO: административный доступ без cookie/пароля, неизменный локальный профиль, CSRF-защита сохраняется. В этот режим нельзя перейти из-за отказа SSO.
|
||||
|
||||
Среда: Windows amd64, Edge/Chromium, изолированные данные и синтетический провайдер. Реальные аккаунты SSO не переключались. Проверка с установленным SSO требует внутреннего клиента и зарегистрированных redirect/origin.
|
||||
|
||||
Повторение: обычные `go test ./...`, `go vet ./...`, `pnpm --dir frontend test`, `pnpm --dir frontend lint`, `pnpm --dir frontend build`. Для браузера: `FILEBROWSER_INTERNAL_QA=1`, `FILEBROWSER_INTERNAL_QA_SCRIPT` — абсолютный путь к `frontend/scripts/check-internal-session.cjs`; также задайте `PLAYWRIGHT_MODULE`, `BROWSER_EXECUTABLE`, `FILEBROWSER_QA_OUTPUT`. Запуск: `go test ./http -run TestInternalSessionBrowser -v -count=1`.
|
||||
@@ -7,7 +7,7 @@
|
||||
- Удалены JSON/password, no-auth, proxy и hook способы входа, регистрация, выпуск и продление JWT File Browser. Локальные пароли в существующей базе при миграции заменяются заблокированным значением.
|
||||
- OIDC Authorization Code с PKCE S256, state, nonce, RS256, issuer/audience/expiry и at_hash. Идентичность привязана к issuer и sub; совпадение имени с локальным пользователем не повышает права.
|
||||
- Административная роль берётся только из подтверждённого SSO-входа: Master Admin / FS Admin. Флаг admin в локальном профиле не даёт административный доступ.
|
||||
- Сессии в памяти сервера: случайные 256-битные идентификаторы, SHA256 на сервере, Secure/HttpOnly/SameSite=Lax cookie на HTTPS, 8 часов максимум и 30 минут бездействия. Logout немедленно инвалидирует локальную сессию.
|
||||
- С версии 3.2.0: host-only Secure/HttpOnly cookie с внутренним handle; свежий resolve для каждого защищённого запроса, общий logout и защита изменений ожидаемым session_state. Самостоятельных локальных SSO-сессий нет.
|
||||
- Проверка Origin и специального заголовка для меняющих состояние запросов, запрет cross-site запросов. CSP с nonce для HTML bootstrap, запрет скриптов при выдаче пользовательских файлов, nosniff.
|
||||
- Выполнение команд и файловые хуки принудительно выключены; /api/command не зарегистрирован. Внешние симлинки запрещены. Старый вспомогательный CLI-код локальных аккаунтов не подключён к корневой команде; часть legacy-кода оставлена отключённой.
|
||||
- Короткие ссылки: валидация имени, атомарная вставка в BoltDB, отказ 409 при занятом имени; случайные ключи увеличены с 48 до 128 бит.
|
||||
@@ -18,7 +18,7 @@
|
||||
|
||||
## Результаты
|
||||
|
||||
- go test ./... — успешно на Windows, включая OIDC, роли, logout, expiry/idle, CSRF, callback replay, короткие ссылки и конкурентную вставку.
|
||||
- go test ./... — успешно на Windows, включая OIDC, роли, logout, отказе/смене аккаунта, CSRF, callback replay, короткие ссылки и конкурентную вставку.
|
||||
- go vet ./... — успешно.
|
||||
- Frontend: TypeScript, production build, 29 тестов и ESLint без ошибок — успешно. У старых неизменённых файлов при полном lint остаются предупреждения Prettier из-за CRLF-выгрузки Windows.
|
||||
- pnpm audit — 0 известных уязвимостей в установленном дереве.
|
||||
@@ -27,9 +27,7 @@
|
||||
|
||||
## Ограничения эксплуатации
|
||||
|
||||
Согласно выбранной схеме VTNL Panel, изменение роли или блокировка в SSO не отзывает уже созданную сессию File Browser до нового входа/истечения срока. Сам SSO не менялся. Для немедленного завершения всех локальных сессий перезапустите приложение.
|
||||
|
||||
Сессии хранятся в памяти одного процесса; после перезапуска нужен новый вход. Несколько экземпляров требуют sticky sessions. Долгая операция, начатая до истечения сессии, не обрывается посередине; новая операция потребует действующую сессию.
|
||||
Новый контракт и проверки общей сессии описаны в [авторизации](authentication.md). При недоступности SSO доступ закрыт без резервной локальной авторизации. Режим без входа включается только явным `--no-sso` и предоставляет всем посетителям административный доступ.
|
||||
|
||||
Debian-бинарник собирается из Windows для linux/amd64 с отключённым CGO и GOAMD64=v1. Нативный запуск и тесты на Debian в этой среде не выполнялись. POSIX-тест с именами, содержащими обратные слеши, не применим к файловой системе Windows и пропускается там.
|
||||
|
||||
|
||||
+20
-12
@@ -1,21 +1,29 @@
|
||||
# Вход через SSO
|
||||
# Авторизация
|
||||
|
||||
При входе профиль дополнительно загружается через OIDC UserInfo: имя пользователя, полное имя и email. `sub` обязан совпадать с проверенным ID token; роли берутся только из подписанного токена. Внутренний ключ `sso:…` хранится отдельно от отображаемого имени и не изменяется при сохранении настроек.
|
||||
## Общая сессия SSO
|
||||
|
||||
Повторный вход использует тот же локальный ID. Если предыдущая версия уже создала несколько записей с одинаковым ключом, используется запись с действующим индексом; при утраченном индексе — самая ранняя. Существующие дубли, их настройки и публичные ссылки автоматически не удаляются. В списке пользователей отображаются ID записей. Перед обновлением сохраните резервную копию базы.
|
||||
File Browser использует внутренний контракт общей браузерной сессии. В SSO приложение должно иметь тип **«Внутреннее»**, PKCE S256 и точный callback. Настройка — через `filebrowser init`; секрет хранится только в конфигурации сервера.
|
||||
|
||||
Поддерживается OpenID Connect Authorization Code Flow с PKCE S256. Настройка выполняется через `filebrowser init`, который создаёт `.filebrowser.json` и печатает callback URL. Подробности — [установка](deployment.md).
|
||||
Первичный вход: discovery → Authorization Code + PKCE S256 с `internal_sync=1`. Проверяются одноразовый state, nonce, RS256/JWKS, issuer, audience, exp и at_hash. Параллельные попытки входа имеют отдельные cookies. Для восстановления привязки доступен `prompt=none`; при необходимости фактора продолжается обычный поток без принудительного запроса пароля.
|
||||
|
||||
Проверяются state, nonce, RSA-подпись, issuer, audience, срок действия ID token и привязка access token через at_hash. Идентичность привязана к issuer и стабильному sub. Логин или почта, совпавшие с прежним локальным аккаунтом, не дают доступ к нему.
|
||||
SSO выдаёт `session_handle`. Он хранится в собственной cookie `__Host-internal_session`: Secure, HttpOnly, SameSite=Lax, Path=/, без Domain. Срок не превышает выданный SSO и 30 суток. Cookie не заменяет родительскую сессию SSO и не продлевает её. Access/ID tokens и watch не сохраняются; handle не передаётся в JavaScript, URL или localStorage.
|
||||
|
||||
Роли из подписанного claim roles:
|
||||
**Каждый защищённый запрос** обращается к `/internal/session/resolve` с Basic client ID/secret. Используются только текущие `sub` и роли из resolve; положительный результат между запросами не кешируется. Локальная база хранит настройки и файловые права, а не самостоятельный вход. Связка issuer + sub сохраняет прежние ID, настройки и ссылки. Роли `Master Admin` и `FS Admin` дают административный доступ.
|
||||
|
||||
- Master Admin — администратор File Browser;
|
||||
- FS Admin — администратор File Browser;
|
||||
- остальные — пользователь с назначенными файловыми разрешениями.
|
||||
`GET /auth/session` возвращает текущий статус и разрешённый профиль без credentials. Копия SDK `internal-session.js` синхронизирует открытые вкладки: смена аккаунта отменяет запросы/загрузки, очищает данные и монтирует интерфейс нового аккаунта. Старые формы отвергаются по `X-FB-Session-State` с `409 session_changed`. TUS-загрузка привязана к аккаунту и версии сессии; продолжить её от другого аккаунта нельзя. Долгие чтения/записи перепроверяются не реже чем при следующем чтении/записи после двух секунд, сохранение Craft — также перед атомарной заменой файла.
|
||||
|
||||
Пароли и регистрация пользователей File Browser, JWT, proxy-auth и hook-auth удалены. Пароли публичных ссылок сохранены. Старые локальные пароли удаляются из базы при миграции; перед обновлением сохраните резервную копию базы.
|
||||
При отказе в доступе данные скрываются; при недостающем факторе предлагается пройти TOTP/Passkey. Подключение фактора выполняется в настройках аккаунта. Ошибка SSO/TLS/ответа закрывает защищённые действия с 503, сохраняя cookie для восстановления. Автоматического перехода на старую локальную сессию нет.
|
||||
|
||||
После входа действует локальная сессия в памяти сервера: максимум 8 часов и 30 минут бездействия. Случайный идентификатор хранится в HttpOnly-cookie, в памяти сервера — его SHA256. Роли фиксируются при входе. SSO не опрашивается при работе с файлами. Изменения роли/блокировки SSO применяются при следующем входе; для завершения всех текущих сессий перезапустите File Browser.
|
||||
Выход — защищённый POST, общий для текущей браузерной сессии SSO. Другие устройства не выходят. Если аккаунт успел смениться, logout получает 409 и не повторяется для нового пользователя. «Сменить аккаунт» сначала выполняет этот выход, затем открывает обычный поток входа.
|
||||
|
||||
Выход немедленно удаляет сессию File Browser; сессия самого SSO остаётся активной. Перезапуск приложения завершает все локальные сессии. Для нескольких экземпляров нужна sticky session-маршрутизация.
|
||||
При обновлении старые восьмичасовые сессии File Browser больше не принимаются. Требуется новая PKCE-привязка; существующий вход SSO обычно позволяет сделать её без повторного пароля. Для всех приложений используйте одинаковый issuer; общие Domain-cookies не нужны.
|
||||
|
||||
## Без входа
|
||||
|
||||
```sh
|
||||
./filebrowser --no-sso
|
||||
```
|
||||
|
||||
Этот явный флаг запускает приложение без SSO и пароля. Все посетители получают права администратора в настроенном файловом корне. Конфигурация SSO и доступность провайдера не проверяются. Настройки локального профиля сохраняются между запусками. Без флага обязательна проверка через SSO; ошибка провайдера режим без входа не включает.
|
||||
|
||||
Пароли публичных ссылок остаются независимыми и работают в обоих режимах.
|
||||
+6
-10
@@ -43,17 +43,13 @@ https://files.anidev.ru/auth/callback
|
||||
|
||||
## Сессии
|
||||
|
||||
После проверенного OIDC-входа действует локальная серверная сессия: максимум
|
||||
8 часов и 30 минут бездействия, как в VTNL Panel. Access token не хранится
|
||||
в браузере и не определяет продолжительность локальной сессии. Роли фиксируются
|
||||
при входе. Изменение роли или блокировка в SSO потребует нового входа; немедленный
|
||||
централизованный отзыв сессий в этой версии не реализован. Для массового завершения
|
||||
локальных сессий перезапустите File Browser; сессии хранятся только в памяти.
|
||||
Несколько экземпляров должны использовать sticky sessions; общая база сессий не предусмотрена.
|
||||
В SSO выберите тип приложения **«Внутреннее»**. Используется общая браузерная сессия: каждый защищённый запрос проверяется через `/internal/session/resolve`, роли и текущий аккаунт обновляются без нового OAuth-обмена. Смена аккаунта и общий выход распространяются на открытые приложения; другие устройства независимы.
|
||||
|
||||
Кнопка выхода немедленно удаляет сессию File Browser. Общая сессия самого SSO остаётся
|
||||
активной, поэтому новый вход может не потребовать пароль. Локальные пароли, регистрация,
|
||||
JWT File Browser, proxy-auth и hook-auth удалены. Пароли **публичных ссылок** сохранены.
|
||||
Конфигурация содержит точный `sso.redirectURI` (мастер заполняет его автоматически). Прежние конфигурации без этого поля используют callback, полученный из `sso.publicURL`. Все приложения установки должны использовать одинаковый issuer. Настройка cookie Domain не требуется; для SSO используйте HTTPS.
|
||||
|
||||
Для запуска без SSO и пароля: `./filebrowser --no-sso`. В этом режиме все посетители получают административный доступ к настроенному корню.
|
||||
|
||||
Подробности и миграция старых сессий: [авторизация](authentication.md).
|
||||
|
||||
## Запуск через systemd
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "filebrowser-frontend",
|
||||
"version": "3.1.0",
|
||||
"version": "3.2.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"engines": {
|
||||
@@ -39,7 +39,7 @@
|
||||
"pinia": "^3.0.4",
|
||||
"pretty-bytes": "^7.2.0",
|
||||
"tus-js-client": "^4.3.1",
|
||||
"utif": "^3.1.0",
|
||||
"utif": "^3.2.0",
|
||||
"video.js": "^8.24.2",
|
||||
"videojs-hotkeys": "^0.2.30",
|
||||
"videojs-mobile-ui": "^1.2.7",
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE);
|
||||
(async () => {
|
||||
const browser = await chromium.launch({
|
||||
executablePath: process.env.BROWSER_EXECUTABLE,
|
||||
headless: true,
|
||||
args: ["--host-resolver-rules=MAP *.localhost 127.0.0.1"],
|
||||
});
|
||||
const output = process.env.FILEBROWSER_QA_OUTPUT;
|
||||
fs.mkdirSync(output, { recursive: true });
|
||||
const errors = [];
|
||||
const contexts = [];
|
||||
const change = async (values) => {
|
||||
const response = await contexts[0].request.post(
|
||||
process.env.QA_ISSUER + "/__qa/change",
|
||||
{
|
||||
headers: { "X-QA-Control": process.env.QA_CONTROL },
|
||||
data: {
|
||||
Name: "Alice",
|
||||
Version: "A-1",
|
||||
Status: "authenticated",
|
||||
Denied: false,
|
||||
Offline: false,
|
||||
...values,
|
||||
},
|
||||
}
|
||||
);
|
||||
assert.equal(response.status(), 204);
|
||||
};
|
||||
try {
|
||||
const context = await browser.newContext({
|
||||
ignoreHTTPSErrors: true,
|
||||
viewport: { width: 1300, height: 900 },
|
||||
locale: "en-US",
|
||||
});
|
||||
contexts.push(context);
|
||||
await context.route("**/internal/session/frame?**", (route) =>
|
||||
route.abort()
|
||||
);
|
||||
const cookies = (device) =>
|
||||
[
|
||||
["one", process.env.QA_APP_ONE],
|
||||
["two", process.env.QA_APP_TWO],
|
||||
].map(([id, url]) => ({
|
||||
name: "__Host-internal_session",
|
||||
value: id + "-" + device + "-binding-123456789",
|
||||
url,
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: "Lax",
|
||||
}));
|
||||
await context.addCookies(cookies("device-one"));
|
||||
const a = await context.newPage(),
|
||||
b = await context.newPage();
|
||||
for (const p of [a, b]) p.on("pageerror", (e) => errors.push(String(e)));
|
||||
await Promise.all([
|
||||
a.goto(process.env.QA_APP_ONE + "/files/"),
|
||||
b.goto(process.env.QA_APP_TWO + "/files/"),
|
||||
]);
|
||||
try {
|
||||
await Promise.all([
|
||||
a.getByText("Alice-private.txt", { exact: true }).waitFor(),
|
||||
b.getByText("Alice-private.txt", { exact: true }).waitFor(),
|
||||
]);
|
||||
} catch (error) {
|
||||
console.log("INITIAL ERRORS", errors);
|
||||
for (const [index, page] of [a, b].entries()) {
|
||||
console.log("BODY", index, await page.locator("body").innerText());
|
||||
console.log(
|
||||
"SESSION",
|
||||
await (
|
||||
await context.request.get(
|
||||
(index === 0 ? process.env.QA_APP_ONE : process.env.QA_APP_TWO) +
|
||||
"/auth/session"
|
||||
)
|
||||
).text()
|
||||
);
|
||||
await page.screenshot({
|
||||
path: path.join(output, `initial-${index}.png`),
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const device2 = await browser.newContext({ ignoreHTTPSErrors: true });
|
||||
contexts.push(device2);
|
||||
await device2.addCookies(cookies("device-two"));
|
||||
const independent = await device2.newPage();
|
||||
await independent.goto(process.env.QA_APP_ONE + "/files/");
|
||||
await independent.getByText("Alice-private.txt", { exact: true }).waitFor();
|
||||
// Hold a valid A response until after both applications have switched to B.
|
||||
let release;
|
||||
const held = new Promise((r) => (release = r));
|
||||
let ready;
|
||||
const captured = new Promise((r) => (ready = r));
|
||||
let didHold = false;
|
||||
await a.route("**/api/resources/", async (route) => {
|
||||
if (didHold) {
|
||||
await route.continue();
|
||||
return;
|
||||
}
|
||||
didHold = true;
|
||||
const response = await route.fetch();
|
||||
ready();
|
||||
await held;
|
||||
await route.fulfill({ response }).catch(() => {});
|
||||
});
|
||||
await a.getByRole("button", { name: "Actions", exact: true }).click();
|
||||
await a.getByRole("menuitem", { name: "Refresh", exact: true }).click();
|
||||
await captured;
|
||||
await change({ Name: "Bob", Version: "B-1" });
|
||||
await Promise.all([
|
||||
a
|
||||
.getByText("Bob-private.txt", { exact: true })
|
||||
.waitFor({ timeout: 15000 }),
|
||||
b
|
||||
.getByText("Bob-private.txt", { exact: true })
|
||||
.waitFor({ timeout: 15000 }),
|
||||
]);
|
||||
release();
|
||||
|
||||
await a.unroute("**/api/resources/");
|
||||
await a.waitForTimeout(200);
|
||||
assert.equal(
|
||||
await a.getByText("Alice-private.txt", { exact: true }).count(),
|
||||
0
|
||||
);
|
||||
assert.equal(
|
||||
await b.getByText("Alice-private.txt", { exact: true }).count(),
|
||||
0
|
||||
);
|
||||
assert(
|
||||
await independent
|
||||
.getByText("Alice-private.txt", { exact: true })
|
||||
.isVisible()
|
||||
);
|
||||
assert(!new URL(a.url()).pathname.startsWith("/auth/"));
|
||||
assert(!new URL(b.url()).pathname.startsWith("/auth/"));
|
||||
await a.screenshot({ path: path.join(output, "account-B.png") });
|
||||
const stale = await context.request.post(
|
||||
process.env.QA_APP_ONE + "/api/resources/stale.txt",
|
||||
{
|
||||
headers: { "X-FB-Request": "1", "X-FB-Session-State": "A-1" },
|
||||
data: "must not write",
|
||||
}
|
||||
);
|
||||
assert.equal(stale.status(), 409);
|
||||
await change({ Name: "Bob", Version: "B-1", Denied: true });
|
||||
await b
|
||||
.getByRole("heading", { name: "Access denied", exact: true })
|
||||
.waitFor({ timeout: 15000 });
|
||||
assert.equal(
|
||||
await b.getByText("Alice-private.txt", { exact: true }).count(),
|
||||
0
|
||||
);
|
||||
assert.equal(
|
||||
await b.getByText("Bob-private.txt", { exact: true }).count(),
|
||||
0
|
||||
);
|
||||
await change({ Name: "Bob", Version: "B-1", Offline: true });
|
||||
await a
|
||||
.getByRole("heading", {
|
||||
name: "Sign-in service unavailable",
|
||||
exact: true,
|
||||
})
|
||||
.waitFor({ timeout: 15000 });
|
||||
assert.equal(
|
||||
await a.getByText("Bob-private.txt", { exact: true }).count(),
|
||||
0
|
||||
);
|
||||
assert(
|
||||
(await context.cookies(process.env.QA_APP_ONE)).some(
|
||||
(c) => c.name === "__Host-internal_session"
|
||||
)
|
||||
);
|
||||
await change({ Name: "Bob", Version: "B-2" });
|
||||
await a
|
||||
.getByText("Bob-private.txt", { exact: true })
|
||||
.waitFor({ timeout: 15000 });
|
||||
const logout = await context.request.post(
|
||||
process.env.QA_APP_ONE + "/auth/logout",
|
||||
{ headers: { "X-FB-Request": "1", "X-FB-Session-State": "B-2" } }
|
||||
);
|
||||
assert.equal(logout.status(), 204);
|
||||
await b
|
||||
.getByRole("heading", { name: "Signed out", exact: true })
|
||||
.waitFor({ timeout: 15000 });
|
||||
assert(
|
||||
await independent
|
||||
.getByText("Alice-private.txt", { exact: true })
|
||||
.isVisible()
|
||||
);
|
||||
await change({ Status: "factor_required", Version: "factor" });
|
||||
await b
|
||||
.getByRole("heading", { name: "Verify your sign-in", exact: true })
|
||||
.waitFor({ timeout: 15000 });
|
||||
assert(!new URL(b.url()).pathname.startsWith("/auth/"));
|
||||
const cookiesAtEnd = await context.cookies(process.env.QA_APP_TWO);
|
||||
const binding = cookiesAtEnd.find(
|
||||
(c) => c.name === "__Host-internal_session"
|
||||
);
|
||||
assert(
|
||||
binding &&
|
||||
binding.secure &&
|
||||
binding.httpOnly &&
|
||||
binding.path === "/" &&
|
||||
!binding.domain.startsWith(".")
|
||||
);
|
||||
assert.equal(errors.length, 0, errors.join("\n"));
|
||||
console.log(
|
||||
"Two apps: A→B, stale form, denied access, outage/recovery, shared logout, missing factor and independent device passed."
|
||||
);
|
||||
} finally {
|
||||
for (const c of contexts) await c.close();
|
||||
await browser.close();
|
||||
}
|
||||
})().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
const fs = require("node:fs"),
|
||||
path = require("node:path"),
|
||||
assert = require("node:assert/strict"),
|
||||
{ spawn } = require("node:child_process");
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE);
|
||||
(async () => {
|
||||
const root = fs.mkdtempSync(
|
||||
path.join(process.env.FILEBROWSER_QA_OUTPUT, "no-sso-")
|
||||
);
|
||||
const files = path.join(root, "files");
|
||||
fs.mkdirSync(files);
|
||||
fs.writeFileSync(path.join(files, "anonymous.txt"), "NO PASSWORD");
|
||||
const config = path.join(root, "config.json"),
|
||||
db = path.join(root, "test.db");
|
||||
fs.writeFileSync(
|
||||
config,
|
||||
JSON.stringify({
|
||||
root: files,
|
||||
database: db,
|
||||
sso: { issuer: "invalid-provider-configuration" },
|
||||
})
|
||||
);
|
||||
const args = [
|
||||
"--config",
|
||||
config,
|
||||
"--root",
|
||||
files,
|
||||
"--database",
|
||||
db,
|
||||
"--port",
|
||||
"0",
|
||||
];
|
||||
const processOne = spawn(process.env.FILEBROWSER_EXE, [...args, "--no-sso"], {
|
||||
cwd: root,
|
||||
windowsHide: true,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
let logs = "",
|
||||
browser;
|
||||
const started = new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(
|
||||
() => reject(Error("startup timeout " + logs)),
|
||||
12000
|
||||
);
|
||||
const read = (chunk) => {
|
||||
logs += chunk.toString();
|
||||
const found = logs.match(/Listening on (127\.0\.0\.1:\d+)/);
|
||||
if (found) {
|
||||
clearTimeout(timeout);
|
||||
resolve("http://" + found[1]);
|
||||
}
|
||||
};
|
||||
processOne.stdout.on("data", read);
|
||||
processOne.stderr.on("data", read);
|
||||
processOne.once("exit", (code) => {
|
||||
clearTimeout(timeout);
|
||||
reject(Error("exited " + code + " " + logs));
|
||||
});
|
||||
});
|
||||
try {
|
||||
const url = await started;
|
||||
browser = await chromium.launch({
|
||||
executablePath: process.env.BROWSER_EXECUTABLE,
|
||||
headless: true,
|
||||
});
|
||||
const context = await browser.newContext();
|
||||
const page = await context.newPage();
|
||||
const response = await context.request.get(url + "/api/session");
|
||||
assert.equal(response.status(), 200);
|
||||
const user = await response.json();
|
||||
assert.equal(user.authMode, "no-sso");
|
||||
assert.equal(user.perm.admin, true);
|
||||
await page.goto(url + "/files/");
|
||||
await page.getByText("anonymous.txt", { exact: true }).waitFor();
|
||||
assert.equal(await page.locator("iframe").count(), 0);
|
||||
assert.equal(await page.locator('a[href$="/auth/account"]').count(), 0);
|
||||
const write = await context.request.post(
|
||||
url + "/api/resources/created.txt",
|
||||
{ headers: { "X-FB-Request": "1" }, data: "CREATED WITHOUT PASSWORD" }
|
||||
);
|
||||
assert.equal(write.status(), 200);
|
||||
assert.equal(
|
||||
fs.readFileSync(path.join(files, "created.txt"), "utf8"),
|
||||
"CREATED WITHOUT PASSWORD"
|
||||
);
|
||||
await page.screenshot({ path: path.join(root, "anonymous-workspace.png") });
|
||||
} finally {
|
||||
if (browser) await browser.close();
|
||||
if (processOne.exitCode === null) {
|
||||
processOne.kill();
|
||||
await new Promise((r) => processOne.once("exit", r));
|
||||
}
|
||||
fs.writeFileSync(path.join(root, "server.log"), logs);
|
||||
}
|
||||
const normal = spawn(process.env.FILEBROWSER_EXE, args, {
|
||||
cwd: root,
|
||||
windowsHide: true,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
let normalLogs = "";
|
||||
normal.stdout.on("data", (d) => (normalLogs += d));
|
||||
normal.stderr.on("data", (d) => (normalLogs += d));
|
||||
const code = await new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
normal.kill();
|
||||
reject(Error("SSO mode unexpectedly started"));
|
||||
}, 12000);
|
||||
normal.once("exit", (code) => {
|
||||
clearTimeout(timer);
|
||||
resolve(code);
|
||||
});
|
||||
});
|
||||
assert.notEqual(code, 0);
|
||||
assert(!normalLogs.includes("Listening on"));
|
||||
console.log(
|
||||
"CLI --no-sso: no provider, cookie or password; reads/writes and administrator UI passed. Without flag, invalid SSO cannot start."
|
||||
);
|
||||
})().catch((e) => {
|
||||
console.error(e);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
+57
-3
@@ -1,22 +1,76 @@
|
||||
<template>
|
||||
<div>
|
||||
<h1 class="sr-only">{{ name }}</h1>
|
||||
<router-view></router-view>
|
||||
<SessionGate v-if="blocked" />
|
||||
<router-view v-else :key="auth.epoch"></router-view>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, watch } from "vue";
|
||||
import { ref, onMounted, onBeforeUnmount, computed, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { setHtmlLocale } from "./i18n";
|
||||
import { getMediaPreference, getTheme, setTheme } from "./utils/theme";
|
||||
import { name } from "./utils/constants";
|
||||
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { acceptSession, setSessionRecheck } from "@/utils/auth";
|
||||
import SessionGate from "@/components/SessionGate.vue";
|
||||
import "@/utils/internal-session.js";
|
||||
import { baseURL, noAuth } from "@/utils/constants";
|
||||
const auth = useAuthStore(),
|
||||
route = useRoute(),
|
||||
router = useRouter();
|
||||
watch(
|
||||
() => auth.user?.id,
|
||||
(id, old) => {
|
||||
if (id && old && id !== old && route.meta.requiresAuth)
|
||||
void router.replace("/files/");
|
||||
}
|
||||
);
|
||||
watch(
|
||||
() => auth.user?.perm.admin,
|
||||
(admin) => {
|
||||
if (admin === false && route.meta.requiresAdmin)
|
||||
void router.replace("/403");
|
||||
}
|
||||
);
|
||||
const blocked = computed(
|
||||
() =>
|
||||
!["Login", "Share"].includes(String(route.name)) &&
|
||||
auth.sessionStatus !== "authenticated"
|
||||
);
|
||||
let sync: { stop: () => void } | undefined;
|
||||
onBeforeUnmount(() => {
|
||||
sync?.stop();
|
||||
setSessionRecheck();
|
||||
});
|
||||
const { locale } = useI18n();
|
||||
|
||||
const userTheme = ref<UserTheme>(getTheme() || getMediaPreference());
|
||||
|
||||
onMounted(() => {
|
||||
onMounted(async () => {
|
||||
await router.isReady();
|
||||
if (
|
||||
!noAuth &&
|
||||
window.FileBrowser.SSOIssuer &&
|
||||
window.FileBrowser.SSOClientID
|
||||
) {
|
||||
const restart = () => {
|
||||
sync?.stop();
|
||||
sync = window.SSOInternalSession.start({
|
||||
issuer: window.FileBrowser.SSOIssuer,
|
||||
clientId: window.FileBrowser.SSOClientID,
|
||||
checkUrl: baseURL + "/auth/session",
|
||||
onChange: acceptSession,
|
||||
onUnavailable: () =>
|
||||
acceptSession({ status: "unavailable", authenticated: false }),
|
||||
});
|
||||
};
|
||||
restart();
|
||||
setSessionRecheck(restart);
|
||||
}
|
||||
setTheme(userTheme.value, false);
|
||||
setHtmlLocale(locale.value);
|
||||
// this might be null during HMR
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { sessionScope, sessionIsCurrent } from "@/utils/session-scope";
|
||||
import { useLayoutStore } from "@/stores/layout";
|
||||
import { baseURL } from "@/utils/constants";
|
||||
import { upload as postTus, useTus } from "./tus";
|
||||
@@ -112,6 +113,7 @@ export async function post(
|
||||
overwrite = false,
|
||||
onupload: any = () => {}
|
||||
) {
|
||||
const scope = sessionScope();
|
||||
// Use the pre-existing API if:
|
||||
const useResourcesApi =
|
||||
// a folder is being created
|
||||
@@ -121,6 +123,7 @@ export async function post(
|
||||
!["http:", "https:"].includes(window.location.protocol)) ||
|
||||
// Tus is disabled / not applicable
|
||||
!(await useTus(content));
|
||||
if (!sessionIsCurrent(scope.generation)) throw new Error("Upload aborted");
|
||||
return useResourcesApi
|
||||
? postResources(url, content, overwrite, onupload)
|
||||
: postTus(url, content, overwrite, onupload);
|
||||
@@ -143,6 +146,7 @@ async function postResources(
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const scope = sessionScope();
|
||||
const request = new XMLHttpRequest();
|
||||
resourceUploads.add(request);
|
||||
request.onloadend = () => resourceUploads.delete(request);
|
||||
@@ -153,12 +157,17 @@ async function postResources(
|
||||
true
|
||||
);
|
||||
request.setRequestHeader("X-FB-Request", "1");
|
||||
request.setRequestHeader("X-FB-Session-State", scope.state);
|
||||
|
||||
if (typeof onupload === "function") {
|
||||
request.upload.onprogress = onupload;
|
||||
}
|
||||
|
||||
request.onload = () => {
|
||||
if (!sessionIsCurrent(scope.generation)) {
|
||||
reject(new Error("Upload aborted"));
|
||||
return;
|
||||
}
|
||||
if (request.status === 200) {
|
||||
resolve(request.responseText);
|
||||
} else if (request.status === 409) {
|
||||
@@ -225,6 +234,7 @@ export function getPreviewURL(file: ResourceItem, size: string) {
|
||||
const params = {
|
||||
inline: "true",
|
||||
key: Date.parse(file.modified),
|
||||
account: sessionScope().generation,
|
||||
};
|
||||
|
||||
return createURL("api/preview/" + size + file.path, params);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { sessionScope } from "@/utils/session-scope";
|
||||
import * as tus from "tus-js-client";
|
||||
import { baseURL, tusEndpoint, tusSettings, origin } from "@/utils/constants";
|
||||
import { removePrefix } from "@/api/utils";
|
||||
@@ -17,6 +18,7 @@ export async function upload(
|
||||
throw new Error("Tus.io settings are not defined");
|
||||
}
|
||||
|
||||
const scope = sessionScope();
|
||||
filePath = removePrefix(filePath);
|
||||
const resourcePath = `${tusEndpoint}${filePath}?override=${overwrite}`;
|
||||
|
||||
@@ -33,6 +35,7 @@ export async function upload(
|
||||
storeFingerprintForResuming: false,
|
||||
headers: {
|
||||
"X-FB-Request": "1",
|
||||
"X-FB-Session-State": scope.state,
|
||||
},
|
||||
onShouldRetry: function (err) {
|
||||
const status = err.originalResponse
|
||||
@@ -40,7 +43,7 @@ export async function upload(
|
||||
: 0;
|
||||
|
||||
// Do not retry for file conflict.
|
||||
if (status === 409 || status === 401 || status === 403) {
|
||||
if ([409, 401, 403, 428, 503].includes(status)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -109,7 +112,9 @@ function isTusSupported() {
|
||||
export function abortAllUploads() {
|
||||
for (const filePath in CURRENT_UPLOAD_LIST) {
|
||||
if (CURRENT_UPLOAD_LIST[filePath]) {
|
||||
CURRENT_UPLOAD_LIST[filePath].abort(true);
|
||||
void CURRENT_UPLOAD_LIST[filePath].abort(true).catch(() => {
|
||||
/* A switched account cannot cancel the previous account's server transfer. */
|
||||
});
|
||||
CURRENT_UPLOAD_LIST[filePath].options!.onError!(
|
||||
new Error("Upload aborted")
|
||||
);
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { startLogin } from "@/utils/auth";
|
||||
import {
|
||||
sessionScope,
|
||||
sessionIsCurrent,
|
||||
mergeSignals,
|
||||
} from "@/utils/session-scope";
|
||||
import { validateLogin, acceptSession } from "@/utils/auth";
|
||||
import { baseURL } from "@/utils/constants";
|
||||
import { encodePath } from "@/utils/url";
|
||||
|
||||
@@ -19,7 +23,7 @@ export async function fetchURL(
|
||||
opts: ApiOpts,
|
||||
auth = true
|
||||
): Promise<Response> {
|
||||
const authStore = useAuthStore();
|
||||
const scope = sessionScope();
|
||||
|
||||
opts = opts || {};
|
||||
opts.headers = opts.headers || {};
|
||||
@@ -30,9 +34,13 @@ export async function fetchURL(
|
||||
res = await fetch(`${baseURL}${url}`, {
|
||||
headers: {
|
||||
"X-FB-Request": "1",
|
||||
"X-FB-Session-State": scope.state,
|
||||
...headers,
|
||||
},
|
||||
...rest,
|
||||
signal: opts.signal
|
||||
? mergeSignals(opts.signal, scope.signal)
|
||||
: scope.signal,
|
||||
});
|
||||
} catch (e) {
|
||||
// Check if the error is an intentional cancellation
|
||||
@@ -42,6 +50,19 @@ export async function fetchURL(
|
||||
throw new StatusError("000 No connection", 0);
|
||||
}
|
||||
|
||||
if (!sessionIsCurrent(scope.generation))
|
||||
throw new StatusError("Session changed", 409, true);
|
||||
for (const method of ["json", "text", "arrayBuffer", "blob"] as const) {
|
||||
const read = res[method].bind(res);
|
||||
Object.defineProperty(res, method, {
|
||||
value: async () => {
|
||||
const result = await read();
|
||||
if (!sessionIsCurrent(scope.generation))
|
||||
throw new StatusError("Session changed", 409, true);
|
||||
return result;
|
||||
},
|
||||
});
|
||||
}
|
||||
if (res.status < 200 || res.status > 299) {
|
||||
const body = await res.text();
|
||||
const error = new StatusError(
|
||||
@@ -49,10 +70,26 @@ export async function fetchURL(
|
||||
res.status
|
||||
);
|
||||
|
||||
if (auth && res.status == 401) {
|
||||
authStore.clearUser();
|
||||
startLogin();
|
||||
if (
|
||||
[401, 403, 409, 428, 503].includes(res.status) &&
|
||||
!url.startsWith("/api/public/")
|
||||
) {
|
||||
try {
|
||||
const state = JSON.parse(body);
|
||||
if (typeof state.status === "string")
|
||||
acceptSession({
|
||||
status:
|
||||
state.status === "session_changed" ? "checking" : state.status,
|
||||
authenticated: false,
|
||||
session_state: state.session_state,
|
||||
required_factors: state.required_factors,
|
||||
});
|
||||
} catch {
|
||||
/* Ordinary file permission errors do not change identity. */
|
||||
}
|
||||
void validateLogin();
|
||||
}
|
||||
void auth;
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
<template>
|
||||
<main class="sso-welcome" role="alert">
|
||||
<div class="sso-symbol"><AppIcon name="account_circle" /></div>
|
||||
<h1>{{ t("session." + message) }}</h1>
|
||||
<p>{{ t("session." + message + "Hint") }}</p>
|
||||
<button
|
||||
v-if="
|
||||
['factor_required', 'rebind_required', 'signed_out'].includes(
|
||||
auth.sessionStatus
|
||||
)
|
||||
"
|
||||
class="button"
|
||||
@click="startLogin(undefined, auth.sessionStatus === 'rebind_required')"
|
||||
>
|
||||
{{ t("session.continue") }}
|
||||
</button>
|
||||
<a
|
||||
v-if="
|
||||
auth.sessionStatus === 'access_denied' ||
|
||||
auth.sessionStatus === 'factor_enrollment_required'
|
||||
"
|
||||
class="button"
|
||||
:href="baseURL + '/auth/account'"
|
||||
>{{ t("preferences.manage") }}</a
|
||||
>
|
||||
<button
|
||||
v-if="auth.sessionStatus === 'unavailable'"
|
||||
class="button"
|
||||
@click="validateLogin"
|
||||
>
|
||||
{{ t("session.retry") }}
|
||||
</button>
|
||||
</main>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { baseURL } from "@/utils/constants";
|
||||
import { startLogin, validateLogin } from "@/utils/auth";
|
||||
const auth = useAuthStore(),
|
||||
{ t } = useI18n();
|
||||
const message = computed(() =>
|
||||
[
|
||||
"checking",
|
||||
"access_denied",
|
||||
"factor_required",
|
||||
"rebind_required",
|
||||
"signed_out",
|
||||
"factor_enrollment_required",
|
||||
].includes(auth.sessionStatus)
|
||||
? auth.sessionStatus
|
||||
: "unavailable"
|
||||
);
|
||||
</script>
|
||||
@@ -113,6 +113,7 @@
|
||||
@keydown="menuKey"
|
||||
>
|
||||
<a
|
||||
v-if="!noAuth"
|
||||
role="menuitem"
|
||||
:href="baseURL + '/auth/account'"
|
||||
@click="navigate"
|
||||
@@ -145,6 +146,9 @@
|
||||
}}</router-link
|
||||
>
|
||||
|
||||
<button v-if="canLogout" role="menuitem" @click="signOut(true)">
|
||||
<AppIcon name="account_circle" />{{ t("session.switchAccount") }}
|
||||
</button>
|
||||
<button v-if="canLogout" role="menuitem" @click="logout">
|
||||
<AppIcon name="logout" />{{ t("sidebar.logout") }}
|
||||
</button>
|
||||
|
||||
@@ -30,6 +30,7 @@ interface IProps {
|
||||
zoomStep?: number;
|
||||
}
|
||||
|
||||
const pendingImages = new Set<XMLHttpRequest>();
|
||||
const props = withDefaults(defineProps<IProps>(), {
|
||||
moveDisabledTime: () => 200,
|
||||
classList: () => [],
|
||||
@@ -88,6 +89,15 @@ onMounted(() => {
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
for (const xhr of pendingImages) {
|
||||
xhr.abort();
|
||||
const i = UTIF._xhrs.indexOf(xhr);
|
||||
if (i >= 0) {
|
||||
UTIF._xhrs.splice(i, 1);
|
||||
UTIF._imgs.splice(i, 1);
|
||||
}
|
||||
}
|
||||
pendingImages.clear();
|
||||
window.removeEventListener("resize", onResize);
|
||||
document.removeEventListener("mouseup", onMouseUp);
|
||||
});
|
||||
@@ -119,11 +129,15 @@ const decodeUTIF = () => {
|
||||
|
||||
if (sufs.indexOf(suff) == -1) return false;
|
||||
const xhr = new XMLHttpRequest();
|
||||
pendingImages.add(xhr);
|
||||
UTIF._xhrs.push(xhr);
|
||||
UTIF._imgs.push(imgex.value);
|
||||
xhr.open("GET", props.src);
|
||||
xhr.responseType = "arraybuffer";
|
||||
xhr.onload = UTIF._imgLoaded;
|
||||
xhr.onload = (event) => {
|
||||
pendingImages.delete(xhr);
|
||||
UTIF._imgLoaded(event);
|
||||
};
|
||||
xhr.send();
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -490,5 +490,24 @@
|
||||
"remaining": "{time} remaining",
|
||||
"seconds": "s",
|
||||
"minutes": "min"
|
||||
},
|
||||
"session": {
|
||||
"checking": "Checking session",
|
||||
"checkingHint": "Verifying your current session.",
|
||||
"access_denied": "Access denied",
|
||||
"access_deniedHint": "The current account cannot access this application.",
|
||||
"factor_required": "Verify your sign-in",
|
||||
"factor_requiredHint": "Complete TOTP or Passkey verification in the sign-in service.",
|
||||
"factor_enrollment_required": "Set up account protection",
|
||||
"factor_enrollment_requiredHint": "Add TOTP or a Passkey in your account settings to continue.",
|
||||
"rebind_required": "Sign-in required",
|
||||
"rebind_requiredHint": "Restore the connection to your current account.",
|
||||
"signed_out": "Signed out",
|
||||
"signed_outHint": "Sign in to continue.",
|
||||
"unavailable": "Sign-in service unavailable",
|
||||
"unavailableHint": "Access is temporarily blocked. Try again later.",
|
||||
"continue": "Continue",
|
||||
"retry": "Retry",
|
||||
"switchAccount": "Switch account"
|
||||
}
|
||||
}
|
||||
@@ -487,5 +487,24 @@
|
||||
"remaining": "Осталось {time}",
|
||||
"seconds": "с",
|
||||
"minutes": "мин"
|
||||
},
|
||||
"session": {
|
||||
"checking": "Проверка входа",
|
||||
"checkingHint": "Проверяем текущую сессию.",
|
||||
"access_denied": "Нет доступа",
|
||||
"access_deniedHint": "У текущего аккаунта нет доступа к этому приложению.",
|
||||
"factor_required": "Подтвердите вход",
|
||||
"factor_requiredHint": "Завершите проверку TOTP или Passkey в сервисе входа.",
|
||||
"factor_enrollment_required": "Подключите защиту аккаунта",
|
||||
"factor_enrollment_requiredHint": "Для доступа необходимо подключить TOTP или Passkey в настройках аккаунта.",
|
||||
"rebind_required": "Требуется вход",
|
||||
"rebind_requiredHint": "Восстановите привязку к текущему аккаунту.",
|
||||
"signed_out": "Вы вышли из аккаунта",
|
||||
"signed_outHint": "Войдите, чтобы продолжить.",
|
||||
"unavailable": "Сервис входа недоступен",
|
||||
"unavailableHint": "Доступ временно закрыт. Повторите проверку позже.",
|
||||
"continue": "Продолжить",
|
||||
"retry": "Повторить",
|
||||
"switchAccount": "Сменить аккаунт"
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,8 @@ app.use(Toast, {
|
||||
newestOnTop: true,
|
||||
} satisfies PluginOptions);
|
||||
|
||||
window.addEventListener("fb-session-boundary", () => useToast().clear());
|
||||
|
||||
app.use(i18n);
|
||||
app.use(pinia);
|
||||
app.use(router);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { sessionScope } from "@/utils/session-scope";
|
||||
import { defineStore } from "pinia";
|
||||
import { fetchJSON } from "@/api/utils";
|
||||
export interface Addon {
|
||||
@@ -17,21 +18,28 @@ export interface Addon {
|
||||
total: number;
|
||||
}
|
||||
let request: Promise<void> | undefined;
|
||||
let requestGeneration = -1;
|
||||
export const useAddonsStore = defineStore("addons", {
|
||||
state: () => ({ items: [] as Addon[], loaded: false }),
|
||||
actions: {
|
||||
async refresh(force = false): Promise<void> {
|
||||
const generation = sessionScope().generation;
|
||||
if (requestGeneration !== generation) {
|
||||
request = undefined;
|
||||
requestGeneration = generation;
|
||||
}
|
||||
if (request)
|
||||
return request.then(() => (force ? this.refresh() : undefined));
|
||||
request = fetchJSON<Addon[]>("/api/addons")
|
||||
const active: Promise<void> = fetchJSON<Addon[]>("/api/addons")
|
||||
.then((items) => {
|
||||
this.items = items;
|
||||
this.loaded = true;
|
||||
})
|
||||
.finally(() => {
|
||||
request = undefined;
|
||||
if (request === active) request = undefined;
|
||||
});
|
||||
return request;
|
||||
request = active;
|
||||
return active;
|
||||
},
|
||||
available(id: string) {
|
||||
return this.items.some(
|
||||
|
||||
@@ -7,9 +7,17 @@ export const useAuthStore = defineStore("auth", {
|
||||
state: (): {
|
||||
user: IUser | null;
|
||||
logoutTimer: number | null;
|
||||
sessionStatus: string;
|
||||
sessionState: string;
|
||||
requiredFactors: string[];
|
||||
epoch: number;
|
||||
} => ({
|
||||
user: null,
|
||||
logoutTimer: null,
|
||||
sessionStatus: "checking",
|
||||
sessionState: "",
|
||||
requiredFactors: [],
|
||||
epoch: 0,
|
||||
}),
|
||||
getters: {
|
||||
isLoggedIn: (state) => state.user !== null,
|
||||
|
||||
@@ -2,9 +2,17 @@ import { createPinia as _createPinia } from "pinia";
|
||||
import { markRaw } from "vue";
|
||||
import type { Router } from "vue-router";
|
||||
|
||||
const accountStores = new Set<any>();
|
||||
export function resetAccountStores() {
|
||||
for (const store of accountStores) {
|
||||
if (["auth", "router", "upload"].includes(store.$id)) continue;
|
||||
store.$reset();
|
||||
}
|
||||
}
|
||||
export default function createPinia(router: Router) {
|
||||
const pinia = _createPinia();
|
||||
pinia.use(({ store }) => {
|
||||
accountStores.add(store);
|
||||
store.router = markRaw(router);
|
||||
});
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ const beforeUnload = (event: Event) => {
|
||||
export const useUploadStore = defineStore("upload", () => {
|
||||
const $showError = inject<IToastError>("$showError")!;
|
||||
|
||||
let generation = 0;
|
||||
let progressInterval: number | null = null;
|
||||
|
||||
//
|
||||
@@ -97,6 +98,7 @@ export const useUploadStore = defineStore("upload", () => {
|
||||
const isActiveUploadsOnLimit = () => activeUploads.value.size < UPLOADS_LIMIT;
|
||||
|
||||
const processUploads = async () => {
|
||||
const started = generation;
|
||||
if (!hasActiveUploads() && !hasPendingUploads()) {
|
||||
const fileStore = useFileStore();
|
||||
window.removeEventListener("beforeunload", beforeUnload);
|
||||
@@ -130,11 +132,12 @@ export const useUploadStore = defineStore("upload", () => {
|
||||
.post(upload.path, upload.file!, upload.overwrite, onUpload)
|
||||
.catch((err) => {
|
||||
succeeded = false;
|
||||
if (err.message !== "Upload aborted") $showError(err);
|
||||
if (generation === started && err.message !== "Upload aborted")
|
||||
$showError(err);
|
||||
});
|
||||
}
|
||||
|
||||
finishUpload(upload, succeeded);
|
||||
if (generation === started) finishUpload(upload, succeeded);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -186,6 +189,12 @@ export const useUploadStore = defineStore("upload", () => {
|
||||
};
|
||||
|
||||
return {
|
||||
resetForAccount() {
|
||||
generation++;
|
||||
abort();
|
||||
reset();
|
||||
window.removeEventListener("beforeunload", beforeUnload);
|
||||
},
|
||||
// STATE
|
||||
activeUploads,
|
||||
totalBytes,
|
||||
|
||||
Vendored
+2
@@ -1,4 +1,6 @@
|
||||
interface IUser {
|
||||
authMode?: string;
|
||||
sessionState?: string;
|
||||
displayName?: string;
|
||||
profileName?: string;
|
||||
email?: string;
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { expect, it, vi } from "vitest";
|
||||
import {
|
||||
changeSessionScope,
|
||||
sessionScope,
|
||||
sessionIsCurrent,
|
||||
scopedFetch,
|
||||
mergeSignals,
|
||||
} from "../session-scope";
|
||||
it("aborts work when account or session state changes, not on an unchanged poll", () => {
|
||||
changeSessionScope("A:one", "one");
|
||||
const a = sessionScope();
|
||||
expect(changeSessionScope("A:one", "one")).toBe(false);
|
||||
expect(a.signal.aborted).toBe(false);
|
||||
changeSessionScope("B:two", "two");
|
||||
expect(a.signal.aborted).toBe(true);
|
||||
expect(sessionIsCurrent(a.generation)).toBe(false);
|
||||
expect(sessionScope().state).toBe("two");
|
||||
});
|
||||
it("rejects an A response arriving after B even when the transport ignores cancellation", async () => {
|
||||
changeSessionScope("A:late", "late");
|
||||
let deliver!: (r: Response) => void;
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(
|
||||
() =>
|
||||
new Promise<Response>((resolve) => {
|
||||
deliver = resolve;
|
||||
})
|
||||
)
|
||||
);
|
||||
const pending = scopedFetch("https://files.test/api/private");
|
||||
changeSessionScope("B:new", "new");
|
||||
deliver(new Response("private A"));
|
||||
await expect(pending).rejects.toMatchObject({ name: "AbortError" });
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("combines cancellation on browsers without AbortSignal.any", () => {
|
||||
vi.stubGlobal("AbortSignal", { any: undefined });
|
||||
try {
|
||||
const first = new AbortController(),
|
||||
second = new AbortController();
|
||||
const signal = mergeSignals(first.signal, second.signal);
|
||||
second.abort();
|
||||
expect(signal.aborted).toBe(true);
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
+71
-20
@@ -1,41 +1,92 @@
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { useUploadStore } from "@/stores/upload";
|
||||
import { resetAccountStores } from "@/stores";
|
||||
import { baseURL } from "./constants";
|
||||
import { setLocale, detectLocale } from "@/i18n";
|
||||
import { changeSessionScope } from "./session-scope";
|
||||
export interface SessionState {
|
||||
status: string;
|
||||
authenticated: boolean;
|
||||
session_state?: string;
|
||||
user?: IUser;
|
||||
required_factors?: string[];
|
||||
}
|
||||
export function startLogin(
|
||||
target = window.location.pathname + window.location.search
|
||||
target = window.location.pathname + window.location.search,
|
||||
silent = false
|
||||
) {
|
||||
window.location.assign(
|
||||
baseURL + "/auth/login?return=" + encodeURIComponent(target)
|
||||
baseURL +
|
||||
"/auth/login?return=" +
|
||||
encodeURIComponent(target) +
|
||||
(silent ? "&silent=1" : "")
|
||||
);
|
||||
}
|
||||
export function acceptSession(state: SessionState) {
|
||||
const auth = useAuthStore();
|
||||
const valid =
|
||||
state.authenticated === true &&
|
||||
!!state.user &&
|
||||
state.status === "authenticated";
|
||||
const next = valid
|
||||
? `${state.user!.id}:${state.session_state}:${JSON.stringify(state.user!.perm)}`
|
||||
: state.status;
|
||||
if (changeSessionScope(next, state.session_state || "")) {
|
||||
// Hide the old account before any new identity or data can be rendered.
|
||||
auth.user = null;
|
||||
useUploadStore().resetForAccount();
|
||||
resetAccountStores();
|
||||
window.dispatchEvent(new Event("fb-session-boundary"));
|
||||
auth.epoch++;
|
||||
}
|
||||
auth.sessionStatus = valid ? "authenticated" : state.status;
|
||||
auth.sessionState = state.session_state || "";
|
||||
auth.requiredFactors = state.required_factors || [];
|
||||
if (valid) auth.setUser(state.user!);
|
||||
else auth.user = null;
|
||||
}
|
||||
let pending: Promise<void> | null = null;
|
||||
let liveRecheck: (() => void) | undefined;
|
||||
export function setSessionRecheck(check?: () => void) {
|
||||
liveRecheck = check;
|
||||
}
|
||||
export function validateLogin(): Promise<void> {
|
||||
if (liveRecheck) {
|
||||
liveRecheck();
|
||||
return Promise.resolve();
|
||||
}
|
||||
if (pending) return pending;
|
||||
pending = (async () => {
|
||||
const res = await fetch(baseURL + "/api/session", {
|
||||
credentials: "same-origin",
|
||||
cache: "no-store",
|
||||
});
|
||||
if (res.ok) {
|
||||
const user = await res.json();
|
||||
useAuthStore().setUser(user);
|
||||
await setLocale(user.locale || detectLocale());
|
||||
} else if (res.status === 401) useAuthStore().clearUser();
|
||||
else throw new Error("SSO session is temporarily unavailable");
|
||||
try {
|
||||
const res = await fetch(baseURL + "/auth/session", {
|
||||
credentials: "same-origin",
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!res.ok) throw new Error("Session unavailable");
|
||||
acceptSession(await res.json());
|
||||
} catch {
|
||||
acceptSession({ status: "unavailable", authenticated: false });
|
||||
}
|
||||
})().finally(() => {
|
||||
pending = null;
|
||||
});
|
||||
return pending;
|
||||
}
|
||||
export async function logout() {
|
||||
export async function logout(switchAccount = false) {
|
||||
const auth = useAuthStore();
|
||||
const res = await fetch(baseURL + "/auth/logout", {
|
||||
method: "POST",
|
||||
headers: { "X-FB-Request": "1" },
|
||||
headers: { "X-FB-Request": "1", "X-FB-Session-State": auth.sessionState },
|
||||
credentials: "same-origin",
|
||||
});
|
||||
if (!res.ok) throw new Error("Sign out failed. Please try again.");
|
||||
useAuthStore().clearUser();
|
||||
localStorage.removeItem("jwt");
|
||||
document.cookie = "auth=; Max-Age=0; Path=/; SameSite=Strict";
|
||||
window.location.assign(baseURL + "/login?logged-out=1");
|
||||
if (res.status === 409) {
|
||||
await validateLogin();
|
||||
return;
|
||||
}
|
||||
if (!res.ok) {
|
||||
await validateLogin();
|
||||
throw new Error("Sign out failed");
|
||||
}
|
||||
acceptSession({ status: "signed_out", authenticated: false });
|
||||
if (switchAccount) startLogin(baseURL + "/files/");
|
||||
else window.location.assign(baseURL + "/login?logged-out=1");
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
import { scopedFetch } from "./session-scope";
|
||||
export async function readDicomFile(source: string, signal: AbortSignal) {
|
||||
const response = await fetch(source, { credentials: "same-origin", signal });
|
||||
const response = await scopedFetch(source, {
|
||||
credentials: "same-origin",
|
||||
signal,
|
||||
});
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
const limit = 64 * 1024 * 1024;
|
||||
if (Number(response.headers.get("Content-Length")) > limit) {
|
||||
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
export {};
|
||||
declare global {
|
||||
interface Window {
|
||||
SSOInternalSession: {
|
||||
start(options: {
|
||||
issuer: string;
|
||||
clientId: string;
|
||||
checkUrl: string;
|
||||
onChange: (state: any) => void;
|
||||
onUnavailable: () => void;
|
||||
}): { check: () => Promise<void>; stop: () => void };
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/* Client SDK. Credentials and session handles belong exclusively on the application's backend. */
|
||||
(() => {
|
||||
window.SSOInternalSession = {
|
||||
start({
|
||||
issuer,
|
||||
clientId,
|
||||
checkUrl,
|
||||
onChange,
|
||||
onUnavailable = () => {},
|
||||
interval = 2000,
|
||||
}) {
|
||||
const authority = new URL(issuer);
|
||||
const endpoint = new URL(checkUrl, location.href);
|
||||
if (
|
||||
endpoint.origin !== location.origin ||
|
||||
authority.username ||
|
||||
authority.password ||
|
||||
(authority.protocol !== "https:" &&
|
||||
!(
|
||||
authority.protocol === "http:" &&
|
||||
["localhost", "127.0.0.1"].includes(authority.hostname)
|
||||
))
|
||||
) {
|
||||
throw new Error("Invalid session configuration");
|
||||
}
|
||||
let stopped = false,
|
||||
pending = false,
|
||||
previous,
|
||||
timer;
|
||||
const controller = new AbortController();
|
||||
const frame = document.createElement("iframe");
|
||||
frame.hidden = true;
|
||||
frame.title = "Session synchronization";
|
||||
const broker = new URL("/internal/session/frame", authority.origin);
|
||||
broker.searchParams.set("client_id", clientId);
|
||||
broker.searchParams.set("origin", location.origin);
|
||||
frame.src = broker.href;
|
||||
async function check() {
|
||||
if (pending || stopped) return;
|
||||
pending = true;
|
||||
try {
|
||||
const response = await fetch(endpoint, {
|
||||
credentials: "same-origin",
|
||||
cache: "no-store",
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (!response.ok) throw new Error("Session unavailable");
|
||||
const state = await response.json();
|
||||
const fingerprint = JSON.stringify(state);
|
||||
if (fingerprint !== previous && !stopped) {
|
||||
previous = fingerprint;
|
||||
onChange(state);
|
||||
}
|
||||
} catch (error) {
|
||||
if (!stopped) {
|
||||
previous = undefined;
|
||||
onUnavailable(error);
|
||||
}
|
||||
} finally {
|
||||
pending = false;
|
||||
}
|
||||
}
|
||||
const message = (event) => {
|
||||
if (
|
||||
event.origin === authority.origin &&
|
||||
event.source === frame.contentWindow &&
|
||||
event.data?.type === "sso:session-changed"
|
||||
)
|
||||
check();
|
||||
};
|
||||
function schedule() {
|
||||
clearTimeout(timer);
|
||||
if (stopped) return;
|
||||
timer = setTimeout(
|
||||
async () => {
|
||||
await check();
|
||||
schedule();
|
||||
},
|
||||
document.hidden ? 10000 : Math.max(1000, interval)
|
||||
);
|
||||
}
|
||||
const focus = () => {
|
||||
check();
|
||||
schedule();
|
||||
};
|
||||
const hide = (event) => {
|
||||
if (!event.persisted) stop();
|
||||
};
|
||||
function stop() {
|
||||
stopped = true;
|
||||
clearTimeout(timer);
|
||||
controller.abort();
|
||||
frame.remove();
|
||||
window.removeEventListener("message", message);
|
||||
window.removeEventListener("focus", focus);
|
||||
document.removeEventListener("visibilitychange", focus);
|
||||
window.removeEventListener("pagehide", hide);
|
||||
window.removeEventListener("pageshow", focus);
|
||||
}
|
||||
window.addEventListener("message", message);
|
||||
window.addEventListener("focus", focus);
|
||||
window.addEventListener("pagehide", hide);
|
||||
window.addEventListener("pageshow", focus);
|
||||
document.addEventListener("visibilitychange", focus);
|
||||
document.body.append(frame);
|
||||
check();
|
||||
schedule();
|
||||
return { check, stop };
|
||||
},
|
||||
};
|
||||
})();
|
||||
@@ -1,3 +1,4 @@
|
||||
import { scopedFetch } from "./session-scope";
|
||||
export type PreviewKind =
|
||||
| "zip"
|
||||
| "pdf"
|
||||
@@ -88,7 +89,10 @@ export async function previewBuffer(
|
||||
signal: AbortSignal,
|
||||
limit = 5 * 1024 * 1024
|
||||
): Promise<ArrayBuffer> {
|
||||
const response = await fetch(source, { credentials: "same-origin", signal });
|
||||
const response = await scopedFetch(source, {
|
||||
credentials: "same-origin",
|
||||
signal,
|
||||
});
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
if (Number(response.headers.get("Content-Length")) > limit) {
|
||||
await response.body?.cancel();
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
// A boundary invalidates all work started by the previous account/state.
|
||||
let generation = 0;
|
||||
let state = "";
|
||||
let key = "";
|
||||
let controller = new AbortController();
|
||||
export function sessionScope() {
|
||||
return { generation, state, signal: controller.signal };
|
||||
}
|
||||
export function sessionIsCurrent(value: number) {
|
||||
return value === generation;
|
||||
}
|
||||
export function changeSessionScope(next: string, version: string) {
|
||||
if (key === next) {
|
||||
state = version;
|
||||
return false;
|
||||
}
|
||||
controller.abort();
|
||||
controller = new AbortController();
|
||||
generation++;
|
||||
key = next;
|
||||
state = version;
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function scopedFetch(
|
||||
input: RequestInfo | URL,
|
||||
options: RequestInit = {}
|
||||
) {
|
||||
const scope = sessionScope();
|
||||
const response = await fetch(input, {
|
||||
...options,
|
||||
signal: options.signal
|
||||
? mergeSignals(options.signal, scope.signal)
|
||||
: scope.signal,
|
||||
});
|
||||
if (!sessionIsCurrent(scope.generation))
|
||||
throw new DOMException("Session changed", "AbortError");
|
||||
return response;
|
||||
}
|
||||
|
||||
// Older browsers may support AbortController without AbortSignal.any.
|
||||
export function mergeSignals(
|
||||
...values: (AbortSignal | undefined | null)[]
|
||||
): AbortSignal {
|
||||
const signals = values.filter((s): s is AbortSignal => !!s);
|
||||
if (signals.length === 1) return signals[0];
|
||||
if (typeof AbortSignal.any === "function") return AbortSignal.any(signals);
|
||||
const combined = new AbortController();
|
||||
const cancel = () => {
|
||||
combined.abort();
|
||||
for (const signal of signals) signal.removeEventListener("abort", cancel);
|
||||
};
|
||||
if (signals.some((s) => s.aborted)) cancel();
|
||||
else
|
||||
for (const signal of signals)
|
||||
signal.addEventListener("abort", cancel, { once: true });
|
||||
return combined.signal;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { scopedFetch } from "./session-scope";
|
||||
// List the central directory only. Never read, inflate or follow file entries.
|
||||
const MAX_DIRECTORY = 4 * 1024 * 1024;
|
||||
const MAX_ENTRIES = 10000;
|
||||
@@ -81,7 +82,7 @@ async function range(
|
||||
size: number,
|
||||
signal: AbortSignal
|
||||
) {
|
||||
const response = await fetch(source, {
|
||||
const response = await scopedFetch(source, {
|
||||
credentials: "same-origin",
|
||||
signal,
|
||||
headers: { Range: `bytes=${start}-${end}` },
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
<template>
|
||||
<main class="sso-welcome">
|
||||
<SessionGate
|
||||
v-if="
|
||||
[
|
||||
'access_denied',
|
||||
'factor_required',
|
||||
'factor_enrollment_required',
|
||||
'unavailable',
|
||||
].includes(auth.sessionStatus)
|
||||
"
|
||||
/>
|
||||
<main v-else class="sso-welcome">
|
||||
<div class="sso-symbol" aria-hidden="true">
|
||||
<AppIcon name="folder_open" />
|
||||
</div>
|
||||
@@ -12,7 +22,9 @@
|
||||
</main>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from "vue";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import SessionGate from "@/components/SessionGate.vue";
|
||||
const auth = useAuthStore();
|
||||
import { useRoute } from "vue-router";
|
||||
import { name, baseURL } from "@/utils/constants";
|
||||
import { startLogin } from "@/utils/auth";
|
||||
@@ -25,7 +37,4 @@ function signIn() {
|
||||
: "/files/")
|
||||
);
|
||||
}
|
||||
onMounted(() => {
|
||||
if (route.query.redirect && !route.query["logged-out"]) signIn();
|
||||
});
|
||||
</script>
|
||||
@@ -8,7 +8,10 @@
|
||||
<p>{{ authStore.user?.email || authStore.user?.username }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<a class="button account-management" :href="baseURL + '/auth/account'"
|
||||
<a
|
||||
v-if="!noAuth"
|
||||
class="button account-management"
|
||||
:href="baseURL + '/auth/account'"
|
||||
>{{ t("preferences.manage") }}<AppIcon name="north_east"
|
||||
/></a>
|
||||
</section>
|
||||
@@ -109,7 +112,7 @@ import { useLayoutStore } from "@/stores/layout";
|
||||
import { users as api } from "@/api";
|
||||
import Languages from "@/components/settings/Languages.vue";
|
||||
import AccountAvatar from "@/components/AccountAvatar.vue";
|
||||
import { baseURL } from "@/utils/constants";
|
||||
import { baseURL, noAuth } from "@/utils/constants";
|
||||
import { getTheme, getMediaPreference, setTheme } from "@/utils/theme";
|
||||
import { dicomPreferences } from "@/utils/dicom-quality";
|
||||
import { detectLocale } from "@/i18n";
|
||||
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
)
|
||||
|
||||
type userInfo struct {
|
||||
SessionState string `json:"sessionState,omitempty"`
|
||||
AuthMode string `json:"authMode,omitempty"`
|
||||
ID uint `json:"id"`
|
||||
Locale string `json:"locale"`
|
||||
ViewMode users.ViewMode `json:"viewMode"`
|
||||
|
||||
@@ -171,6 +171,9 @@ func craftDocumentHandler(manager *addons.Manager, cache FileCache) handleFunc {
|
||||
if err = d.user.Fs.Chmod(tempName, mode); err != nil {
|
||||
return 500, err
|
||||
}
|
||||
if err = checkOperationIdentity(r); err != nil {
|
||||
return http.StatusConflict, err
|
||||
}
|
||||
err = d.RunHook(func() error { return d.user.Fs.Rename(tempName, requested) }, "save", requested, "", d.user)
|
||||
if err != nil {
|
||||
return errToStatus(err), err
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/diskcache"
|
||||
"github.com/filebrowser/filebrowser/v2/frontend"
|
||||
"github.com/filebrowser/filebrowser/v2/img"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// Optional integration: two real File Browser servers, one shared mock issuer,
|
||||
// separate host-only Secure cookies, and a second independent browser device.
|
||||
func TestInternalSessionBrowser(t *testing.T) {
|
||||
if os.Getenv("FILEBROWSER_INTERNAL_QA") != "1" {
|
||||
t.Skip("optional browser integration")
|
||||
}
|
||||
var mu sync.Mutex
|
||||
name, version, status := "Alice", "A-1", "authenticated"
|
||||
denied, offline := false, false
|
||||
control := randomSecret()
|
||||
provider := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/internal/session/frame" {
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Write([]byte("<!doctype html><title>Session notification fixture</title>"))
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if r.URL.Path == "/__qa/change" {
|
||||
if r.Header.Get("X-QA-Control") != control {
|
||||
w.WriteHeader(403)
|
||||
return
|
||||
}
|
||||
var p struct {
|
||||
Name string
|
||||
Version string
|
||||
Status string
|
||||
Denied bool
|
||||
Offline bool
|
||||
}
|
||||
if json.NewDecoder(r.Body).Decode(&p) != nil {
|
||||
w.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
name, version, status, denied, offline = p.Name, p.Version, p.Status, p.Denied, p.Offline
|
||||
w.WriteHeader(204)
|
||||
return
|
||||
}
|
||||
client, secret, ok := r.BasicAuth()
|
||||
if !ok || (client != "one" && client != "two") || secret != "qa-secret" || r.Header.Get("Cookie") != "" {
|
||||
t.Error("unexpected internal credentials or browser cookies")
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
r.ParseForm()
|
||||
if !strings.HasPrefix(r.Form.Get("session_handle"), client+"-") {
|
||||
w.WriteHeader(400)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": "invalid_handle"})
|
||||
return
|
||||
}
|
||||
if offline {
|
||||
w.WriteHeader(503)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/internal/session/logout" {
|
||||
if r.Form.Get("session_state") != version {
|
||||
w.WriteHeader(409)
|
||||
return
|
||||
}
|
||||
status = "signed_out"
|
||||
version = "signed-out"
|
||||
w.WriteHeader(204)
|
||||
return
|
||||
}
|
||||
if r.URL.Path != "/internal/session/resolve" {
|
||||
t.Error("unexpected OAuth exchange or redirect")
|
||||
w.WriteHeader(404)
|
||||
return
|
||||
}
|
||||
who, revision, condition := name, version, status
|
||||
if strings.Contains(r.Form.Get("session_handle"), "device-two") {
|
||||
who, revision, condition = "Alice", "device-two-A", "authenticated"
|
||||
}
|
||||
if denied && client == "two" {
|
||||
condition = "access_denied"
|
||||
}
|
||||
state := internalState{Status: condition, State: revision}
|
||||
if condition == "authenticated" {
|
||||
roles := []string{"User"}
|
||||
if who == "Alice" {
|
||||
roles = []string{"FS Admin"}
|
||||
}
|
||||
state.Authenticated = true
|
||||
state.ClientID = client
|
||||
state.Expires = time.Now().Add(time.Hour).Unix()
|
||||
state.User = &ssoClaims{Subject: who, Username: who, Roles: roles}
|
||||
}
|
||||
json.NewEncoder(w).Encode(state)
|
||||
}))
|
||||
defer provider.Close()
|
||||
assets, err := fs.Sub(frontend.Assets(), "dist")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
urls := []string{}
|
||||
for _, id := range []string{"one", "two"} {
|
||||
root := t.TempDir()
|
||||
for _, who := range []string{"Alice", "Bob"} {
|
||||
os.Mkdir(filepath.Join(root, who), 0750)
|
||||
os.WriteFile(filepath.Join(root, who, who+"-private.txt"), []byte(who+" PRIVATE"), 0600)
|
||||
}
|
||||
st := scopedUserStorage(t, root, users.Permissions{Download: true, Create: true, Rename: true, Modify: true, Delete: true, Share: true}, []byte("key"))
|
||||
st.Users = st.Users.(*customFSUser).Store
|
||||
options, _ := st.Settings.Get()
|
||||
options.Defaults = settings.UserDefaults{Scope: ".", Locale: "en", Perm: users.Permissions{Download: true, Create: true, Rename: true, Modify: true, Delete: true, Share: true}}
|
||||
st.Settings.Save(options)
|
||||
cfg := &settings.Server{Root: root, SSOIssuer: provider.URL, SSOClientID: id}
|
||||
s := &SSO{issuer: provider.URL, store: st, server: cfg, client: provider.Client(), oauth: oauth2.Config{ClientID: id, ClientSecret: "qa-secret"}, avatars: map[string]avatarCache{}, uploads: map[string]uploadBinding{}}
|
||||
for _, who := range []string{"Alice", "Bob"} {
|
||||
i, e := s.provisionUser(ssoClaims{Subject: who, Username: who})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = st.Users.Update(&users.User{ID: i.ID, Scope: who}, "Scope"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
uploads, e := NewUploadCache("")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer uploads.Close()
|
||||
h, e := NewHandler(img.New(1), diskcache.NewNoOp(), uploads, st, cfg, assets)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
app := httptest.NewTLSServer(s.Wrap(h))
|
||||
defer app.Close()
|
||||
url := strings.Replace(app.URL, "127.0.0.1", id+".localhost", 1)
|
||||
s.origin = url
|
||||
urls = append(urls, url)
|
||||
}
|
||||
command := exec.Command("node", os.Getenv("FILEBROWSER_INTERNAL_QA_SCRIPT"))
|
||||
command.Env = append(os.Environ(), "QA_APP_ONE="+urls[0], "QA_APP_TWO="+urls[1], "QA_ISSUER="+provider.URL, "QA_CONTROL="+control)
|
||||
out, err := command.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("%v\n%s", err, out)
|
||||
}
|
||||
t.Log(string(out))
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
func TestInternalSessionTwoApplicationsAndAccountBoundaries(t *testing.T) {
|
||||
user, state, status := "A", "version-A", "authenticated"
|
||||
mode := ""
|
||||
resolves, logouts := 0, 0
|
||||
provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Cookie") != "" {
|
||||
t.Error("forwarded browser cookies")
|
||||
}
|
||||
client, secret, ok := r.BasicAuth()
|
||||
if !ok || (client != "one" && client != "two") || secret != "secret" {
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
r.ParseForm()
|
||||
handle := r.Form.Get("session_handle")
|
||||
if r.URL.Path == "/internal/session/logout" {
|
||||
logouts++
|
||||
if r.Form.Get("session_state") != state {
|
||||
w.WriteHeader(409)
|
||||
return
|
||||
}
|
||||
status = "signed_out"
|
||||
w.WriteHeader(204)
|
||||
return
|
||||
}
|
||||
resolves++
|
||||
if handle == "foreign-handle-000000000000" {
|
||||
w.WriteHeader(400)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": "invalid_handle"})
|
||||
return
|
||||
}
|
||||
if mode == "client-auth" {
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
if mode == "unavailable" {
|
||||
w.WriteHeader(503)
|
||||
return
|
||||
}
|
||||
if mode == "malformed" {
|
||||
w.Write([]byte("not-json"))
|
||||
return
|
||||
}
|
||||
current, version, condition := user, state, status
|
||||
if strings.HasPrefix(handle, "device-two-") {
|
||||
current, version, condition = "A", "device-two-A", "authenticated"
|
||||
}
|
||||
response := internalState{Status: condition, State: version, Factors: []string{"totp"}}
|
||||
if condition == "authenticated" {
|
||||
response.Authenticated = true
|
||||
response.ClientID = client
|
||||
response.Expires = time.Now().Add(time.Hour).Unix()
|
||||
response.User = &ssoClaims{Subject: current, Username: current, Roles: []string{"User"}}
|
||||
}
|
||||
switch mode {
|
||||
case "wrong-client":
|
||||
response.ClientID = "other"
|
||||
case "expired":
|
||||
response.Expires = time.Now().Add(-time.Minute).Unix()
|
||||
case "empty-sub":
|
||||
response.User.Subject = ""
|
||||
case "leaked-user":
|
||||
response.Status = "signed_out"
|
||||
response.Authenticated = false
|
||||
}
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}))
|
||||
defer provider.Close()
|
||||
type application struct {
|
||||
s *SSO
|
||||
h http.Handler
|
||||
}
|
||||
apps := []application{}
|
||||
mutations := []string{}
|
||||
for _, client := range []string{"one", "two"} {
|
||||
root := t.TempDir()
|
||||
st := scopedUserStorage(t, root, users.Permissions{Create: true, Download: true}, []byte("key"))
|
||||
s := &SSO{issuer: provider.URL, origin: "https://" + client + ".test", store: st, server: &settings.Server{Root: root}, client: provider.Client(), oauth: oauth2.Config{ClientID: client, ClientSecret: "secret"}, avatars: map[string]avatarCache{}, uploads: map[string]uploadBinding{}}
|
||||
h := s.Wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
i, ok := r.Context().Value(identityKey{}).(sessionIdentity)
|
||||
if !ok {
|
||||
t.Error("missing identity")
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
if r.Method == "POST" {
|
||||
mutations = append(mutations, i.Sub)
|
||||
}
|
||||
w.Header().Set("X-Subject", i.Sub)
|
||||
w.WriteHeader(204)
|
||||
}))
|
||||
apps = append(apps, application{s, h})
|
||||
}
|
||||
request := func(app int, method, path, expected, handle string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(method, path, nil)
|
||||
r.AddCookie(&http.Cookie{Name: internalCookie, Value: handle})
|
||||
r.Header.Set("X-FB-Request", "1")
|
||||
if expected != "" {
|
||||
r.Header.Set("X-FB-Session-State", expected)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
apps[app].h.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
handle := "device-one-handle-000000000"
|
||||
for i := range apps {
|
||||
w := request(i, "GET", "/api/private", "", handle)
|
||||
if w.Code != 204 || w.Header().Get("X-Subject") != "A" {
|
||||
t.Fatalf("app %d did not resolve A: %d", i, w.Code)
|
||||
}
|
||||
}
|
||||
user, state = "B", "version-B"
|
||||
for i := range apps {
|
||||
w := request(i, "GET", "/api/private", "", handle)
|
||||
if w.Code != 204 || w.Header().Get("X-Subject") != "B" {
|
||||
t.Fatalf("app %d kept old identity", i)
|
||||
}
|
||||
}
|
||||
if w := request(0, "GET", "/api/private", "", "device-two-handle-00000000"); w.Header().Get("X-Subject") != "A" {
|
||||
t.Fatal("another device was switched")
|
||||
}
|
||||
if w := request(0, "POST", "/api/private", "version-A", handle); w.Code != 409 || len(mutations) != 0 {
|
||||
t.Fatal("old form changed data as B")
|
||||
}
|
||||
if w := request(0, "POST", "/api/private", "version-B", handle); w.Code != 204 || len(mutations) != 1 || mutations[0] != "B" {
|
||||
t.Fatal("current form rejected")
|
||||
}
|
||||
for _, condition := range []string{"access_denied", "signed_out", "factor_required", "factor_enrollment_required", "rebind_required"} {
|
||||
status = condition
|
||||
w := request(0, "GET", "/auth/session", "", handle)
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"status":"`+condition+`"`) || strings.Contains(w.Body.String(), `"user"`) {
|
||||
t.Fatalf("bad state %s: %d %s", condition, w.Code, w.Body.String())
|
||||
}
|
||||
if p := request(0, "POST", "/api/private", "version-B", handle); p.Code == 204 {
|
||||
t.Fatal("inactive identity retained access")
|
||||
}
|
||||
}
|
||||
status = "authenticated"
|
||||
for _, failure := range []string{"client-auth", "unavailable", "malformed", "wrong-client", "expired", "empty-sub", "leaked-user"} {
|
||||
mode = failure
|
||||
w := request(0, "GET", "/auth/session", "", handle)
|
||||
if w.Code != 503 || len(w.Result().Cookies()) != 0 {
|
||||
t.Fatalf("%s must fail closed without deleting cookie: %d", failure, w.Code)
|
||||
}
|
||||
}
|
||||
mode = ""
|
||||
if w := request(0, "GET", "/auth/session", "", "foreign-handle-000000000000"); w.Code != 200 || !strings.Contains(w.Body.String(), "rebind_required") {
|
||||
t.Fatal("foreign handle accepted")
|
||||
}
|
||||
before := resolves
|
||||
request(0, "GET", "/api/private", "", handle)
|
||||
request(0, "GET", "/api/private", "", handle)
|
||||
if resolves-before != 2 {
|
||||
t.Fatal("positive identity was cached between requests")
|
||||
}
|
||||
if w := request(0, "POST", "/auth/logout", "version-A", handle); w.Code != 409 || logouts != 0 {
|
||||
t.Fatal("stale logout reached provider")
|
||||
}
|
||||
if w := request(0, "POST", "/auth/logout", "version-B", handle); w.Code != 204 {
|
||||
t.Fatal("global logout failed")
|
||||
}
|
||||
if w := request(1, "GET", "/api/private", "", handle); w.Code != 401 {
|
||||
t.Fatal("second app retained access after logout")
|
||||
}
|
||||
if w := request(0, "GET", "/api/private", "", "device-two-handle-00000000"); w.Code != 204 {
|
||||
t.Fatal("logout affected another device")
|
||||
}
|
||||
status, user, state = "authenticated", "A", "version-A"
|
||||
if w := request(0, "POST", "/api/tus/upload.bin", state, handle); w.Code != 204 {
|
||||
t.Fatal("upload did not start")
|
||||
}
|
||||
user, state = "B", "version-B"
|
||||
if w := request(0, "PATCH", "/api/tus/upload.bin", state, handle); w.Code != 409 {
|
||||
t.Fatal("B continued A's transfer")
|
||||
}
|
||||
user, state = "A", "version-A2"
|
||||
if w := request(0, "PATCH", "/api/tus/upload.bin", state, handle); w.Code != 409 {
|
||||
t.Fatal("old transfer crossed a session-state boundary")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoSSOIsExplicitAndDoesNotNeedProvider(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
st := scopedUserStorage(t, root, users.Permissions{}, []byte("key"))
|
||||
server := &settings.Server{Root: root}
|
||||
n, err := NewNoSSO(st, server)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := n.Wrap(handle(withAdmin(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) { return http.StatusNoContent, nil }), "", st, server))
|
||||
for _, method := range []string{"GET", "POST"} {
|
||||
r := httptest.NewRequest(method, "/api/private", nil)
|
||||
r.Header.Set("X-FB-Request", "1")
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != 204 {
|
||||
t.Fatalf("passwordless mode: %d", w.Code)
|
||||
}
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, httptest.NewRequest("GET", "/auth/session", nil))
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"authMode":"no-sso"`) || !strings.Contains(w.Body.String(), `"admin":true`) {
|
||||
t.Fatal(w.Body.String())
|
||||
}
|
||||
r := httptest.NewRequest("POST", "/api/private", nil)
|
||||
r.Header.Set("Origin", "https://evil.test")
|
||||
w = httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != 403 {
|
||||
t.Fatal("cross-origin passwordless write allowed")
|
||||
}
|
||||
u, err := st.Users.Get(root, false, "local:no-sso")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
n2, err := NewNoSSO(st, server)
|
||||
if err != nil || n2.identity.ID != u.ID {
|
||||
t.Fatal("no-sso created duplicate local user")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLongOperationRevalidatesIdentity(t *testing.T) {
|
||||
provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
json.NewEncoder(w).Encode(internalState{Status: "signed_out"})
|
||||
}))
|
||||
defer provider.Close()
|
||||
s := &SSO{issuer: provider.URL, client: provider.Client()}
|
||||
g := &identityGuard{s: s, identity: sessionIdentity{Sub: "A", State: "state", Handle: "long-operation-handle-00000"}, last: time.Now().Add(-3 * time.Second)}
|
||||
if g.check(context.Background()) == nil {
|
||||
t.Fatal("long connection retained revoked access")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParallelLoginTransactionsHaveSeparateBrowserCookies(t *testing.T) {
|
||||
s := &SSO{base: "", cookiePath: "/", secure: true, attempts: map[string]loginAttempt{}, oauth: oauth2.Config{ClientID: "client", Endpoint: oauth2.Endpoint{AuthURL: "https://sso.test/oauth/authorize"}}}
|
||||
first, second := httptest.NewRecorder(), httptest.NewRecorder()
|
||||
s.login(first, httptest.NewRequest("GET", "/auth/login", nil))
|
||||
s.login(second, httptest.NewRequest("GET", "/auth/login?silent=1", nil))
|
||||
a, b := first.Result().Cookies()[0], second.Result().Cookies()[0]
|
||||
if a.Name == b.Name || a.Value == b.Value || len(s.attempts) != 2 {
|
||||
t.Fatal("parallel flows overwrite each other")
|
||||
}
|
||||
if !a.HttpOnly || !a.Secure || a.SameSite != http.SameSiteLaxMode {
|
||||
t.Fatal("unprotected transaction cookie")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
fberrors "github.com/filebrowser/filebrowser/v2/errors"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/storage"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
// This mode is selected only by an explicit process flag, never by failed SSO.
|
||||
type NoSSO struct {
|
||||
store *storage.Storage
|
||||
server *settings.Server
|
||||
identity sessionIdentity
|
||||
}
|
||||
|
||||
func NewNoSSO(store *storage.Storage, server *settings.Server) (*NoSSO, error) {
|
||||
u, err := store.Users.Get(server.Root, false, "local:no-sso")
|
||||
if errors.Is(err, fberrors.ErrNotExist) {
|
||||
st, e := store.Settings.Get()
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
u = &users.User{Username: "local:no-sso", Password: "!sso-disabled", LockPassword: true}
|
||||
st.Defaults.Apply(u)
|
||||
u.Scope = "/"
|
||||
u.Perm.Admin = false
|
||||
u.Perm.Execute = false
|
||||
u.Commands = []string{}
|
||||
if e = store.Users.SaveProvisioned(u, false); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
} else if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
server.NoSSO = true
|
||||
return &NoSSO{store: store, server: server, identity: sessionIdentity{ID: u.ID, Name: "Local", Admin: true, Sub: "local:no-sso", State: "local"}}, nil
|
||||
}
|
||||
func (n *NoSSO) Wrap(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
p := strings.TrimPrefix(r.URL.Path, n.server.BaseURL)
|
||||
if strings.HasPrefix(p, "/api/") || strings.HasPrefix(p, "/auth/") {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
}
|
||||
if isMutation(r) && !csrfAllowed(r, "") {
|
||||
http.Error(w, "Cross-origin request rejected", 403)
|
||||
return
|
||||
}
|
||||
if p == "/auth/session" || p == "/api/session" {
|
||||
if r.Method != "GET" {
|
||||
w.WriteHeader(405)
|
||||
return
|
||||
}
|
||||
u, err := n.store.Users.Get(n.server.Root, false, n.identity.ID)
|
||||
if err != nil {
|
||||
writeState(w, 503, browserState{Status: "unavailable"})
|
||||
return
|
||||
}
|
||||
applySSOIdentity(u, n.identity)
|
||||
profile := ssoUserInfo(u)
|
||||
profile.AuthMode = "no-sso"
|
||||
profile.SessionState = "local"
|
||||
if p == "/auth/session" {
|
||||
writeState(w, 200, browserState{Status: "authenticated", Authenticated: true, State: "local", User: &profile})
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(profile)
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(p, "/auth/") {
|
||||
if p == "/auth/login" && r.Method == "GET" {
|
||||
http.Redirect(w, r, n.server.BaseURL+"/files/", 303)
|
||||
} else {
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, disabled := range []string{"/api/login", "/api/signup", "/api/renew", "/api/command"} {
|
||||
if p == disabled {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), identityKey{}, n.identity)))
|
||||
})
|
||||
}
|
||||
+19
-256
@@ -5,7 +5,6 @@ import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
@@ -28,6 +27,9 @@ type sessionIdentity struct {
|
||||
Admin bool
|
||||
Name string
|
||||
Picture string
|
||||
Sub string
|
||||
State string
|
||||
Handle string `json:"-"`
|
||||
}
|
||||
type ssoClaims struct {
|
||||
Subject string `json:"sub"`
|
||||
@@ -40,16 +42,10 @@ type ssoClaims struct {
|
||||
type loginAttempt struct {
|
||||
Nonce, Verifier, ReturnTo string
|
||||
Expires time.Time
|
||||
}
|
||||
type ssoSession struct {
|
||||
sync.Mutex
|
||||
Identity sessionIdentity
|
||||
Expires time.Time
|
||||
Touched time.Time
|
||||
Silent bool
|
||||
}
|
||||
|
||||
// SSO owns opaque server-side sessions (8h absolute, 30m idle). Roles are
|
||||
// captured at login. Provider tokens are discarded after OIDC verification.
|
||||
// Identities are resolved afresh from the browser binding for every request.
|
||||
type SSO struct {
|
||||
provider *oidc.Provider
|
||||
verifier *oidc.IDTokenVerifier
|
||||
@@ -57,17 +53,20 @@ type SSO struct {
|
||||
origin, base, cookiePath string
|
||||
secure bool
|
||||
issuer string
|
||||
client *http.Client
|
||||
store *storage.Storage
|
||||
server *settings.Server
|
||||
mu sync.Mutex
|
||||
provision sync.Mutex
|
||||
userIDs map[string]uint
|
||||
attempts map[string]loginAttempt
|
||||
sessions map[[32]byte]*ssoSession
|
||||
avatars map[string]avatarCache
|
||||
uploads map[string]uploadBinding
|
||||
}
|
||||
|
||||
type SSOConfig struct {
|
||||
Issuer string `json:"issuer"`
|
||||
RedirectURI string `json:"redirectURI,omitempty"`
|
||||
ClientID string `json:"clientID"`
|
||||
ClientSecret string `json:"clientSecret"`
|
||||
PublicURL string `json:"publicURL"`
|
||||
@@ -90,7 +89,7 @@ func NewSSO(ctx context.Context, store *storage.Storage, server *settings.Server
|
||||
if base != strings.TrimRight(server.BaseURL, "/") {
|
||||
return nil, errors.New("sso.publicURL path must match baseURL")
|
||||
}
|
||||
client := &http.Client{Timeout: 15 * time.Second}
|
||||
client := &http.Client{Timeout: 10 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
ctx = oidc.ClientContext(ctx, client)
|
||||
provider, err := oidc.NewProvider(ctx, strings.TrimRight(issuer, "/"))
|
||||
if err != nil {
|
||||
@@ -98,8 +97,15 @@ func NewSSO(ctx context.Context, store *storage.Storage, server *settings.Server
|
||||
}
|
||||
endpoint := provider.Endpoint()
|
||||
endpoint.AuthStyle = oauth2.AuthStyleInHeader
|
||||
s := &SSO{provider: provider, verifier: provider.Verifier(&oidc.Config{ClientID: clientID, SupportedSigningAlgs: []string{oidc.RS256}}), origin: u.Scheme + "://" + u.Host, base: base, cookiePath: base + "/", secure: u.Scheme == "https", issuer: strings.TrimRight(issuer, "/"), store: store, server: server, attempts: map[string]loginAttempt{}, sessions: map[[32]byte]*ssoSession{}}
|
||||
s := &SSO{provider: provider, verifier: provider.Verifier(&oidc.Config{ClientID: clientID, SupportedSigningAlgs: []string{oidc.RS256}}), origin: u.Scheme + "://" + u.Host, base: base, cookiePath: base + "/", secure: u.Scheme == "https", issuer: strings.TrimRight(issuer, "/"), store: store, server: server, attempts: map[string]loginAttempt{}, client: client, avatars: map[string]avatarCache{}, uploads: map[string]uploadBinding{}}
|
||||
s.oauth = oauth2.Config{ClientID: clientID, ClientSecret: secret, Endpoint: endpoint, RedirectURL: strings.TrimRight(publicURL, "/") + "/auth/callback", Scopes: []string{oidc.ScopeOpenID, "profile", "email"}}
|
||||
if config.RedirectURI != "" {
|
||||
if config.RedirectURI != s.oauth.RedirectURL {
|
||||
return nil, errors.New("sso.redirectURI must exactly match publicURL/auth/callback")
|
||||
}
|
||||
s.oauth.RedirectURL = config.RedirectURI
|
||||
}
|
||||
server.SSOIssuer, server.SSOClientID = s.issuer, clientID
|
||||
// Remove usable local credentials when migrating an existing installation.
|
||||
legacy, err := store.Users.Gets(server.Root, false)
|
||||
if err != nil && !errors.Is(err, fberrors.ErrNotExist) {
|
||||
@@ -155,149 +161,6 @@ func ssoAdmin(roles []string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (s *SSO) cleanupLocked() {
|
||||
now := time.Now()
|
||||
for k, a := range s.attempts {
|
||||
if now.After(a.Expires) {
|
||||
delete(s.attempts, k)
|
||||
}
|
||||
}
|
||||
for k, v := range s.sessions {
|
||||
if !now.Before(v.Expires) {
|
||||
delete(s.sessions, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SSO) login(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "GET" {
|
||||
w.WriteHeader(405)
|
||||
return
|
||||
}
|
||||
state := randomSecret()
|
||||
a := loginAttempt{Nonce: randomSecret(), Verifier: oauth2.GenerateVerifier(), Expires: time.Now().Add(10 * time.Minute), ReturnTo: s.base + "/files/"}
|
||||
if target := r.URL.Query().Get("return"); strings.HasPrefix(target, s.base+"/") && !strings.HasPrefix(target, "//") && !strings.ContainsAny(target, "\\\r\n") && !strings.HasPrefix(target, s.base+"/auth/") && !strings.HasPrefix(target, s.base+"/login") {
|
||||
a.ReturnTo = target
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.cleanupLocked()
|
||||
if len(s.attempts) >= 1000 {
|
||||
s.mu.Unlock()
|
||||
http.Error(w, "Too many sign-in attempts", 429)
|
||||
return
|
||||
}
|
||||
s.attempts[state] = a
|
||||
s.mu.Unlock()
|
||||
s.cookie(w, "fb_login", state, 600)
|
||||
http.Redirect(w, r, s.oauth.AuthCodeURL(state, oidc.Nonce(a.Nonce), oauth2.S256ChallengeOption(a.Verifier)), http.StatusFound)
|
||||
}
|
||||
|
||||
func (s *SSO) callback(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "GET" {
|
||||
w.WriteHeader(405)
|
||||
return
|
||||
}
|
||||
if len(r.URL.Query()["state"]) != 1 || len(r.URL.Query()["code"]) != 1 {
|
||||
http.Error(w, "Invalid callback parameters", 400)
|
||||
return
|
||||
}
|
||||
state := r.URL.Query().Get("state")
|
||||
c, err := r.Cookie("fb_login")
|
||||
if err != nil || state == "" || c.Value != state {
|
||||
http.Error(w, "Invalid sign-in state", 400)
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
a, ok := s.attempts[state]
|
||||
delete(s.attempts, state)
|
||||
s.mu.Unlock()
|
||||
s.cookie(w, "fb_login", "", -1)
|
||||
if !ok || time.Now().After(a.Expires) {
|
||||
http.Error(w, "Sign-in expired. Please try again.", 400)
|
||||
return
|
||||
}
|
||||
ctx := oidc.ClientContext(r.Context(), &http.Client{Timeout: 15 * time.Second})
|
||||
token, err := s.oauth.Exchange(ctx, r.URL.Query().Get("code"), oauth2.VerifierOption(a.Verifier))
|
||||
if err != nil {
|
||||
http.Error(w, "SSO code exchange failed", 401)
|
||||
return
|
||||
}
|
||||
raw, _ := token.Extra("id_token").(string)
|
||||
id, err := s.verifier.Verify(ctx, raw)
|
||||
if err != nil || id.Nonce != a.Nonce {
|
||||
http.Error(w, "Invalid SSO identity", 401)
|
||||
return
|
||||
}
|
||||
if err = id.VerifyAccessToken(token.AccessToken); err != nil {
|
||||
http.Error(w, "Invalid SSO token binding", 401)
|
||||
return
|
||||
}
|
||||
var claims ssoClaims
|
||||
if err = id.Claims(&claims); err != nil || claims.Subject == "" {
|
||||
http.Error(w, "Invalid SSO claims", 401)
|
||||
return
|
||||
}
|
||||
if token.Expiry.IsZero() || time.Now().After(token.Expiry) {
|
||||
http.Error(w, "Invalid SSO expiry", 401)
|
||||
return
|
||||
}
|
||||
// Fetch profile data as VTNL Panel does, retaining signed identity and roles.
|
||||
var metadata struct {
|
||||
UserInfoURL string `json:"userinfo_endpoint"`
|
||||
}
|
||||
if err = s.provider.Claims(&metadata); err != nil {
|
||||
http.Error(w, "Invalid SSO metadata", 401)
|
||||
return
|
||||
}
|
||||
if metadata.UserInfoURL != "" {
|
||||
profile, profileErr := s.provider.UserInfo(ctx, oauth2.StaticTokenSource(token))
|
||||
if profileErr != nil || profile.Subject != claims.Subject {
|
||||
http.Error(w, "Invalid SSO profile", 401)
|
||||
return
|
||||
}
|
||||
var info ssoClaims
|
||||
if err = profile.Claims(&info); err != nil {
|
||||
http.Error(w, "Invalid SSO profile claims", 401)
|
||||
return
|
||||
}
|
||||
if claims.Username == "" {
|
||||
claims.Username = info.Username
|
||||
}
|
||||
if claims.Name == "" {
|
||||
claims.Name = info.Name
|
||||
}
|
||||
if claims.Email == "" {
|
||||
claims.Email = info.Email
|
||||
}
|
||||
if claims.Picture == "" {
|
||||
claims.Picture = info.Picture
|
||||
}
|
||||
}
|
||||
identity, err := s.provisionUser(claims)
|
||||
if err != nil {
|
||||
http.Error(w, "Cannot provision SSO user", 500)
|
||||
return
|
||||
}
|
||||
identity.Picture = s.loadAvatar(ctx, claims.Picture)
|
||||
sid := randomSecret()
|
||||
key := sha256.Sum256([]byte(sid))
|
||||
s.mu.Lock()
|
||||
s.cleanupLocked()
|
||||
if len(s.sessions) >= 10000 {
|
||||
s.mu.Unlock()
|
||||
http.Error(w, "Too many sessions", 503)
|
||||
return
|
||||
}
|
||||
if old, e := r.Cookie("fb_session"); e == nil {
|
||||
delete(s.sessions, sha256.Sum256([]byte(old.Value)))
|
||||
}
|
||||
expires := time.Now().Add(8 * time.Hour)
|
||||
s.sessions[key] = &ssoSession{Identity: identity, Expires: expires, Touched: time.Now()}
|
||||
s.mu.Unlock()
|
||||
s.cookie(w, "fb_session", sid, int(time.Until(expires).Seconds()))
|
||||
http.Redirect(w, r, a.ReturnTo, http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func (s *SSO) provisionUser(c ssoClaims) (sessionIdentity, error) {
|
||||
s.provision.Lock()
|
||||
defer s.provision.Unlock()
|
||||
@@ -348,107 +211,7 @@ func (s *SSO) provisionUser(c ssoClaims) (sessionIdentity, error) {
|
||||
return sessionIdentity{}, err
|
||||
}
|
||||
}
|
||||
return sessionIdentity{ID: u.ID, Name: name, Admin: ssoAdmin(c.Roles)}, nil
|
||||
}
|
||||
|
||||
func (s *SSO) identify(r *http.Request) (sessionIdentity, bool) {
|
||||
c, err := r.Cookie("fb_session")
|
||||
if err != nil {
|
||||
return sessionIdentity{}, false
|
||||
}
|
||||
key := sha256.Sum256([]byte(c.Value))
|
||||
s.mu.Lock()
|
||||
session := s.sessions[key]
|
||||
s.mu.Unlock()
|
||||
if session == nil {
|
||||
return sessionIdentity{}, false
|
||||
}
|
||||
session.Lock()
|
||||
defer session.Unlock()
|
||||
valid := time.Now().Before(session.Expires) && time.Since(session.Touched) < 30*time.Minute
|
||||
if !valid {
|
||||
s.mu.Lock()
|
||||
delete(s.sessions, key)
|
||||
s.mu.Unlock()
|
||||
return sessionIdentity{}, false
|
||||
}
|
||||
session.Touched = time.Now()
|
||||
return session.Identity, true
|
||||
}
|
||||
|
||||
func (s *SSO) Wrap(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
p := strings.TrimPrefix(r.URL.Path, s.base)
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Referrer-Policy", "same-origin")
|
||||
if strings.HasPrefix(p, "/api/") || strings.HasPrefix(p, "/auth/") {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
}
|
||||
if r.Method != "GET" && r.Method != "HEAD" && r.Method != "OPTIONS" {
|
||||
origin := r.Header.Get("Origin")
|
||||
if (origin != "" && origin != s.origin) || (origin == "" && r.Header.Get("X-FB-Request") != "1") || r.Header.Get("Sec-Fetch-Site") == "cross-site" {
|
||||
http.Error(w, "Cross-origin request rejected", 403)
|
||||
return
|
||||
}
|
||||
}
|
||||
switch p {
|
||||
case "/auth/account":
|
||||
if r.Method != http.MethodGet {
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, strings.TrimRight(s.issuer, "/")+"/settings", http.StatusFound)
|
||||
return
|
||||
case "/auth/login":
|
||||
s.login(w, r)
|
||||
return
|
||||
case "/auth/callback":
|
||||
s.callback(w, r)
|
||||
return
|
||||
case "/auth/logout":
|
||||
if r.Method != "POST" {
|
||||
w.WriteHeader(405)
|
||||
return
|
||||
}
|
||||
if c, e := r.Cookie("fb_session"); e == nil {
|
||||
s.mu.Lock()
|
||||
delete(s.sessions, sha256.Sum256([]byte(c.Value)))
|
||||
s.mu.Unlock()
|
||||
}
|
||||
s.cookie(w, "fb_session", "", -1)
|
||||
w.WriteHeader(204)
|
||||
return
|
||||
case "/api/login", "/api/signup", "/api/renew", "/api/command":
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
identity, ok := s.identify(r)
|
||||
if p == "/api/session" {
|
||||
if r.Method != "GET" {
|
||||
w.WriteHeader(405)
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
u, err := s.store.Users.Get(s.server.Root, s.server.FollowExternalSymlinks, identity.ID)
|
||||
if err != nil {
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
applySSOIdentity(u, identity)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
profile := ssoUserInfo(u)
|
||||
profile.Picture = identity.Picture
|
||||
_ = json.NewEncoder(w).Encode(profile)
|
||||
return
|
||||
}
|
||||
if ok {
|
||||
r = r.WithContext(context.WithValue(r.Context(), identityKey{}, identity))
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
return sessionIdentity{ID: u.ID, Name: name, Admin: ssoAdmin(c.Roles), Sub: c.Subject}, nil
|
||||
}
|
||||
|
||||
func applySSOIdentity(u *users.User, i sessionIdentity) {
|
||||
|
||||
@@ -0,0 +1,476 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
const internalCookie = "__Host-internal_session"
|
||||
|
||||
type internalState struct {
|
||||
Status string `json:"status"`
|
||||
Authenticated bool `json:"authenticated"`
|
||||
ClientID string `json:"client_id,omitempty"`
|
||||
State string `json:"session_state,omitempty"`
|
||||
Expires int64 `json:"expires_at,omitempty"`
|
||||
User *ssoClaims `json:"user,omitempty"`
|
||||
Factors []string `json:"required_factors,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
type browserState struct {
|
||||
Status string `json:"status"`
|
||||
Authenticated bool `json:"authenticated"`
|
||||
State string `json:"session_state,omitempty"`
|
||||
User *userInfo `json:"user,omitempty"`
|
||||
Factors []string `json:"required_factors,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
type uploadBinding struct {
|
||||
State string
|
||||
Expires time.Time
|
||||
}
|
||||
type avatarCache struct {
|
||||
Image string
|
||||
Until time.Time
|
||||
}
|
||||
|
||||
func loginCookieName(state string) string {
|
||||
h := sha256.Sum256([]byte(state))
|
||||
return "fb_login_" + base64.RawURLEncoding.EncodeToString(h[:12])
|
||||
}
|
||||
func writeState(w http.ResponseWriter, code int, state browserState) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(code)
|
||||
_ = json.NewEncoder(w).Encode(state)
|
||||
}
|
||||
func (s *SSO) bindingCookie(w http.ResponseWriter, value string, age int) {
|
||||
http.SetCookie(w, &http.Cookie{Name: internalCookie, Value: value, Path: "/", Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode, MaxAge: age})
|
||||
}
|
||||
func (s *SSO) login(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
w.WriteHeader(405)
|
||||
return
|
||||
}
|
||||
state := randomSecret()
|
||||
a := loginAttempt{Nonce: randomSecret(), Verifier: oauth2.GenerateVerifier(), Expires: time.Now().Add(10 * time.Minute), ReturnTo: s.base + "/files/", Silent: r.URL.Query().Get("silent") == "1"}
|
||||
if target := r.URL.Query().Get("return"); strings.HasPrefix(target, s.base+"/") && !strings.HasPrefix(target, "//") && !strings.ContainsAny(target, "\\\r\n") && !strings.HasPrefix(target, s.base+"/auth/") && !strings.HasPrefix(target, s.base+"/login") {
|
||||
a.ReturnTo = target
|
||||
}
|
||||
s.mu.Lock()
|
||||
for k, v := range s.attempts {
|
||||
if time.Now().After(v.Expires) {
|
||||
delete(s.attempts, k)
|
||||
}
|
||||
}
|
||||
if len(s.attempts) >= 1000 {
|
||||
s.mu.Unlock()
|
||||
http.Error(w, "Too many sign-in attempts", 429)
|
||||
return
|
||||
}
|
||||
s.attempts[state] = a
|
||||
s.mu.Unlock()
|
||||
s.cookie(w, loginCookieName(state), state, 600)
|
||||
options := []oauth2.AuthCodeOption{oidc.Nonce(a.Nonce), oauth2.S256ChallengeOption(a.Verifier), oauth2.SetAuthURLParam("internal_sync", "1")}
|
||||
if a.Silent {
|
||||
options = append(options, oauth2.SetAuthURLParam("prompt", "none"))
|
||||
}
|
||||
http.Redirect(w, r, s.oauth.AuthCodeURL(state, options...), http.StatusFound)
|
||||
}
|
||||
func (s *SSO) callback(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
w.WriteHeader(405)
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
state := q.Get("state")
|
||||
if len(q["state"]) != 1 || state == "" || len(state) > 256 {
|
||||
http.Error(w, "Invalid sign-in state", 400)
|
||||
return
|
||||
}
|
||||
c, err := r.Cookie(loginCookieName(state))
|
||||
if err != nil || c.Value != state {
|
||||
http.Error(w, "Invalid sign-in state", 400)
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
a, ok := s.attempts[state]
|
||||
delete(s.attempts, state)
|
||||
s.mu.Unlock()
|
||||
s.cookie(w, loginCookieName(state), "", -1)
|
||||
if !ok || time.Now().After(a.Expires) {
|
||||
http.Error(w, "Sign-in expired", 400)
|
||||
return
|
||||
}
|
||||
if q.Get("error") != "" {
|
||||
if a.Silent && q.Get("error") == "interaction_required" {
|
||||
http.Redirect(w, r, s.base+"/auth/login?return="+url.QueryEscape(a.ReturnTo), 303)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, s.base+"/login?status=interaction_required", 303)
|
||||
return
|
||||
}
|
||||
if len(q["code"]) != 1 || q.Get("code") == "" {
|
||||
http.Error(w, "Invalid callback parameters", 400)
|
||||
return
|
||||
}
|
||||
ctx := oidc.ClientContext(r.Context(), s.client)
|
||||
token, err := s.oauth.Exchange(ctx, q.Get("code"), oauth2.VerifierOption(a.Verifier))
|
||||
if err != nil {
|
||||
http.Error(w, "SSO code exchange failed", 401)
|
||||
return
|
||||
}
|
||||
raw, _ := token.Extra("id_token").(string)
|
||||
id, err := s.verifier.Verify(ctx, raw)
|
||||
if err != nil || id.Nonce != a.Nonce {
|
||||
http.Error(w, "Invalid SSO identity", 401)
|
||||
return
|
||||
}
|
||||
if id.VerifyAccessToken(token.AccessToken) != nil {
|
||||
http.Error(w, "Invalid SSO token binding", 401)
|
||||
return
|
||||
}
|
||||
var claims ssoClaims
|
||||
if id.Claims(&claims) != nil || strings.TrimSpace(claims.Subject) == "" {
|
||||
http.Error(w, "Invalid SSO claims", 401)
|
||||
return
|
||||
}
|
||||
handle, _ := token.Extra("session_handle").(string)
|
||||
age, err := strconv.ParseFloat(strings.TrimSpace(toScalarString(token.Extra("session_handle_expires_in"))), 64)
|
||||
if err != nil || age < 1 || age > 30*24*60*60 || !validHandle(handle) {
|
||||
http.Error(w, "Internal SSO binding missing; configure an internal client", 502)
|
||||
return
|
||||
}
|
||||
// No provider access token, ID token or watch credential survives this request.
|
||||
s.bindingCookie(w, handle, int(age))
|
||||
s.cookie(w, "fb_session", "", -1)
|
||||
http.Redirect(w, r, a.ReturnTo, http.StatusSeeOther)
|
||||
}
|
||||
func toScalarString(v any) string { b, _ := json.Marshal(v); return strings.Trim(string(b), `"`) }
|
||||
func validHandle(v string) bool {
|
||||
return len(v) >= 16 && len(v) <= 4096 && !strings.ContainsAny(v, "\r\n\x00; ")
|
||||
}
|
||||
|
||||
func (s *SSO) internalCall(ctx context.Context, endpoint string, form url.Values) (*http.Response, error) {
|
||||
r, err := http.NewRequestWithContext(ctx, http.MethodPost, s.issuer+endpoint, strings.NewReader(form.Encode()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.SetBasicAuth(s.oauth.ClientID, s.oauth.ClientSecret)
|
||||
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
return s.client.Do(r)
|
||||
}
|
||||
func (s *SSO) resolve(ctx context.Context, handle string) (internalState, error) {
|
||||
if handle == "" {
|
||||
return internalState{Status: "rebind_required"}, nil
|
||||
}
|
||||
if !validHandle(handle) {
|
||||
return internalState{Status: "rebind_required"}, nil
|
||||
}
|
||||
res, err := s.internalCall(ctx, "/internal/session/resolve", url.Values{"session_handle": {handle}})
|
||||
if err != nil {
|
||||
return internalState{}, errors.New("SSO unavailable")
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if res.StatusCode == 400 {
|
||||
var failure struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
if json.NewDecoder(io.LimitReader(res.Body, 8192)).Decode(&failure) == nil && failure.Error == "invalid_handle" {
|
||||
return internalState{Status: "rebind_required"}, nil
|
||||
}
|
||||
return internalState{}, errors.New("Invalid SSO response")
|
||||
}
|
||||
if res.StatusCode != 200 {
|
||||
return internalState{}, errors.New("SSO unavailable or client configuration invalid")
|
||||
}
|
||||
b, err := io.ReadAll(io.LimitReader(res.Body, 128*1024+1))
|
||||
var state internalState
|
||||
if err != nil || len(b) > 128*1024 || json.Unmarshal(b, &state) != nil {
|
||||
return internalState{}, errors.New("Invalid SSO response")
|
||||
}
|
||||
if state.Authenticated {
|
||||
if state.Status != "authenticated" || state.ClientID != s.oauth.ClientID || state.Expires <= time.Now().Unix() || state.State == "" || len(state.State) > 1024 || state.User == nil || strings.TrimSpace(state.User.Subject) == "" || len(state.User.Subject) > 512 {
|
||||
return internalState{}, errors.New("Invalid SSO identity")
|
||||
}
|
||||
} else {
|
||||
if state.User != nil {
|
||||
return internalState{}, errors.New("Invalid signed-out SSO response")
|
||||
}
|
||||
switch state.Status {
|
||||
case "signed_out", "access_denied", "factor_required", "rebind_required", "factor_enrollment_required":
|
||||
default:
|
||||
return internalState{}, errors.New("Unknown SSO status")
|
||||
}
|
||||
}
|
||||
return state, nil
|
||||
}
|
||||
func (s *SSO) current(r *http.Request) (browserState, sessionIdentity, error) {
|
||||
handle := ""
|
||||
if c, e := r.Cookie(internalCookie); e == nil {
|
||||
handle = c.Value
|
||||
}
|
||||
state, err := s.resolve(r.Context(), handle)
|
||||
if err != nil {
|
||||
return browserState{}, sessionIdentity{}, err
|
||||
}
|
||||
view := browserState{Status: state.Status, Authenticated: state.Authenticated, State: state.State, Factors: state.Factors, Reason: state.Reason}
|
||||
if !state.Authenticated {
|
||||
return view, sessionIdentity{}, nil
|
||||
}
|
||||
i, err := s.provisionUser(*state.User)
|
||||
if err != nil {
|
||||
return browserState{}, sessionIdentity{}, errors.New("Cannot load current user")
|
||||
}
|
||||
i.State, i.Handle = state.State, handle
|
||||
u, err := s.store.Users.Get(s.server.Root, s.server.FollowExternalSymlinks, i.ID)
|
||||
if err != nil {
|
||||
return browserState{}, sessionIdentity{}, errors.New("Cannot load current profile")
|
||||
}
|
||||
applySSOIdentity(u, i)
|
||||
profile := ssoUserInfo(u)
|
||||
profile.SessionState = state.State
|
||||
profile.AuthMode = "sso"
|
||||
key := state.User.Subject + "\x00" + state.User.Picture
|
||||
if state.User.Picture != "" {
|
||||
s.mu.Lock()
|
||||
avatar, ok := s.avatars[key]
|
||||
s.mu.Unlock()
|
||||
if !ok || time.Now().After(avatar.Until) {
|
||||
avatar = avatarCache{Image: s.loadAvatar(r.Context(), state.User.Picture), Until: time.Now().Add(5 * time.Minute)}
|
||||
s.mu.Lock()
|
||||
if len(s.avatars) > 1000 {
|
||||
s.avatars = map[string]avatarCache{}
|
||||
}
|
||||
s.avatars[key] = avatar
|
||||
s.mu.Unlock()
|
||||
}
|
||||
profile.Picture = avatar.Image
|
||||
}
|
||||
view.User = &profile
|
||||
return view, i, nil
|
||||
}
|
||||
|
||||
func isMutation(r *http.Request) bool {
|
||||
return r.Method != "GET" && r.Method != "HEAD" && r.Method != "OPTIONS"
|
||||
}
|
||||
func csrfAllowed(r *http.Request, origin string) bool {
|
||||
if r.Header.Get("Sec-Fetch-Site") == "cross-site" {
|
||||
return false
|
||||
}
|
||||
actual := r.Header.Get("Origin")
|
||||
if actual == "" {
|
||||
return r.Header.Get("X-FB-Request") == "1"
|
||||
}
|
||||
if origin != "" {
|
||||
return actual == origin
|
||||
}
|
||||
u, err := url.Parse(actual)
|
||||
return err == nil && u.User == nil && u.Host == r.Host && (u.Scheme == "https" || u.Scheme == "http")
|
||||
}
|
||||
func privatePath(p string) bool {
|
||||
return (strings.HasPrefix(p, "/api/") && !strings.HasPrefix(p, "/api/public/")) || strings.HasPrefix(p, "/addons/")
|
||||
}
|
||||
|
||||
func (s *SSO) Wrap(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
p := strings.TrimPrefix(r.URL.Path, s.base)
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Referrer-Policy", "same-origin")
|
||||
if strings.HasPrefix(p, "/api/") || strings.HasPrefix(p, "/auth/") {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
}
|
||||
if isMutation(r) && !csrfAllowed(r, s.origin) {
|
||||
http.Error(w, "Cross-origin request rejected", 403)
|
||||
return
|
||||
}
|
||||
switch p {
|
||||
case "/auth/login":
|
||||
s.login(w, r)
|
||||
return
|
||||
case "/auth/callback":
|
||||
s.callback(w, r)
|
||||
return
|
||||
case "/auth/account":
|
||||
if r.Method != "GET" {
|
||||
w.WriteHeader(405)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, s.issuer+"/settings", 302)
|
||||
return
|
||||
case "/api/login", "/api/signup", "/api/renew", "/api/command":
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
check := p == "/auth/session" || p == "/api/session"
|
||||
logout := p == "/auth/logout"
|
||||
if (check && r.Method != "GET") || (logout && r.Method != "POST") {
|
||||
w.WriteHeader(405)
|
||||
return
|
||||
}
|
||||
if !check && !logout && !privatePath(p) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
state, identity, err := s.current(r)
|
||||
if err != nil {
|
||||
writeState(w, 503, browserState{Status: "unavailable"})
|
||||
return
|
||||
}
|
||||
if p == "/auth/session" {
|
||||
writeState(w, 200, state)
|
||||
return
|
||||
}
|
||||
if !state.Authenticated {
|
||||
code := 401
|
||||
if state.Status == "access_denied" || state.Status == "factor_enrollment_required" {
|
||||
code = 403
|
||||
}
|
||||
if state.Status == "factor_required" {
|
||||
code = 428
|
||||
}
|
||||
writeState(w, code, state)
|
||||
return
|
||||
}
|
||||
expected := r.Header.Get("X-FB-Session-State")
|
||||
if (isMutation(r) || expected != "") && expected != identity.State {
|
||||
writeState(w, 409, browserState{Status: "session_changed"})
|
||||
return
|
||||
}
|
||||
if logout {
|
||||
response, e := s.internalCall(r.Context(), "/internal/session/logout", url.Values{"session_handle": {identity.Handle}, "session_state": {identity.State}})
|
||||
if e != nil {
|
||||
writeState(w, 503, browserState{Status: "unavailable"})
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode == 409 {
|
||||
writeState(w, 409, browserState{Status: "session_changed"})
|
||||
return
|
||||
}
|
||||
if response.StatusCode != 204 {
|
||||
writeState(w, 503, browserState{Status: "unavailable"})
|
||||
return
|
||||
}
|
||||
s.bindingCookie(w, "", -1)
|
||||
s.cookie(w, "fb_session", "", -1)
|
||||
w.WriteHeader(204)
|
||||
return
|
||||
}
|
||||
if p == "/api/session" {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(state.User)
|
||||
return
|
||||
}
|
||||
// A TUS transfer belongs to the account/state that created it, even if
|
||||
// two accounts share the same filesystem scope and destination path.
|
||||
if strings.HasPrefix(p, "/api/tus/") {
|
||||
key := identity.Sub + "\x00" + p
|
||||
s.mu.Lock()
|
||||
owner, exists := s.uploads[key]
|
||||
if r.Method == "POST" {
|
||||
for k, v := range s.uploads {
|
||||
if time.Now().After(v.Expires) {
|
||||
delete(s.uploads, k)
|
||||
}
|
||||
}
|
||||
if len(s.uploads) > 10000 {
|
||||
s.mu.Unlock()
|
||||
http.Error(w, "Too many transfers", 503)
|
||||
return
|
||||
}
|
||||
owner = uploadBinding{State: identity.State, Expires: time.Now().Add(time.Hour)}
|
||||
s.uploads[key] = owner
|
||||
exists = true
|
||||
}
|
||||
if exists && owner.State == identity.State && time.Now().Before(owner.Expires) {
|
||||
owner.Expires = time.Now().Add(time.Hour)
|
||||
s.uploads[key] = owner
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if !exists || owner.State != identity.State || time.Now().After(owner.Expires) {
|
||||
writeState(w, 409, browserState{Status: "session_changed"})
|
||||
return
|
||||
}
|
||||
}
|
||||
r = r.WithContext(context.WithValue(r.Context(), identityKey{}, identity))
|
||||
guard := &identityGuard{s: s, identity: identity, last: time.Now()}
|
||||
r = r.WithContext(context.WithValue(r.Context(), guardKey{}, guard))
|
||||
if isMutation(r) && r.Body != nil {
|
||||
r.Body = &guardedBody{ReadCloser: r.Body, guard: guard, ctx: r.Context()}
|
||||
}
|
||||
next.ServeHTTP(&guardedResponse{ResponseWriter: w, guard: guard, ctx: r.Context()}, r)
|
||||
})
|
||||
}
|
||||
|
||||
type guardKey struct{}
|
||||
type identityGuard struct {
|
||||
s *SSO
|
||||
identity sessionIdentity
|
||||
last time.Time
|
||||
}
|
||||
|
||||
func (g *identityGuard) check(ctx context.Context) error { return g.verify(ctx, false) }
|
||||
func (g *identityGuard) verify(ctx context.Context, force bool) error {
|
||||
if !force && time.Since(g.last) < 2*time.Second {
|
||||
return nil
|
||||
}
|
||||
state, err := g.s.resolve(ctx, g.identity.Handle)
|
||||
if err != nil || !state.Authenticated || state.User.Subject != g.identity.Sub || state.State != g.identity.State {
|
||||
return errors.New("session changed or unavailable")
|
||||
}
|
||||
g.last = time.Now()
|
||||
return nil
|
||||
}
|
||||
func checkOperationIdentity(r *http.Request) error {
|
||||
if g, ok := r.Context().Value(guardKey{}).(*identityGuard); ok {
|
||||
return g.verify(r.Context(), true)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type guardedBody struct {
|
||||
io.ReadCloser
|
||||
guard *identityGuard
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func (b *guardedBody) Read(p []byte) (int, error) {
|
||||
if err := b.guard.check(b.ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return b.ReadCloser.Read(p)
|
||||
}
|
||||
|
||||
type guardedResponse struct {
|
||||
http.ResponseWriter
|
||||
guard *identityGuard
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func (w *guardedResponse) Write(p []byte) (int, error) {
|
||||
if err := w.guard.check(w.ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return w.ResponseWriter.Write(p)
|
||||
}
|
||||
func (w *guardedResponse) Unwrap() http.ResponseWriter { return w.ResponseWriter }
|
||||
func (w *guardedResponse) Flush() {
|
||||
if w.guard.check(w.ctx) == nil {
|
||||
if f, ok := w.ResponseWriter.(http.Flusher); ok {
|
||||
f.Flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
+32
-17
@@ -42,6 +42,8 @@ func TestOIDCSessionLifecycle(t *testing.T) {
|
||||
profileSubject := "subject-123"
|
||||
roles := []string{"FS Admin"}
|
||||
enabled := true
|
||||
invalidNonce := false
|
||||
signedOut := false
|
||||
provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
@@ -63,10 +65,31 @@ func TestOIDCSessionLifecycle(t *testing.T) {
|
||||
}
|
||||
hash := sha256.Sum256([]byte("access"))
|
||||
claims := map[string]any{"iss": issuer, "aud": "client", "sub": "subject-123", "roles": roles, "nonce": nonce, "exp": time.Now().Add(5 * time.Minute).Unix(), "iat": time.Now().Unix(), "at_hash": base64.RawURLEncoding.EncodeToString(hash[:16])}
|
||||
if invalidNonce {
|
||||
claims["nonce"] = "wrong"
|
||||
}
|
||||
b, _ := json.Marshal(claims)
|
||||
signed, _ := signer.Sign(b)
|
||||
token, _ := signed.CompactSerialize()
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"access_token": "access", "id_token": token, "token_type": "Bearer", "expires_in": 300})
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"access_token": "access", "id_token": token, "token_type": "Bearer", "expires_in": 300, "session_handle": "test-browser-handle-123456789", "session_handle_expires_in": 2592000})
|
||||
case "/internal/session/resolve":
|
||||
r.ParseForm()
|
||||
if id, secret, ok := r.BasicAuth(); !ok || id != "client" || secret != "secret" || r.Form.Get("session_handle") != "test-browser-handle-123456789" {
|
||||
t.Error("invalid internal resolve request")
|
||||
}
|
||||
if signedOut {
|
||||
json.NewEncoder(w).Encode(internalState{Status: "signed_out"})
|
||||
return
|
||||
}
|
||||
if !enabled {
|
||||
json.NewEncoder(w).Encode(internalState{Status: "access_denied"})
|
||||
return
|
||||
}
|
||||
json.NewEncoder(w).Encode(internalState{Status: "authenticated", Authenticated: true, ClientID: "client", State: "state-1", Expires: time.Now().Add(time.Hour).Unix(), User: &ssoClaims{Subject: profileSubject, Username: "alice", Name: "Alice Example", Email: "alice@example.test", Picture: issuer + "/avatars/alice.png", Roles: roles}})
|
||||
case "/internal/session/logout":
|
||||
signedOut = true
|
||||
w.WriteHeader(204)
|
||||
|
||||
case "/userinfo":
|
||||
if !enabled {
|
||||
w.WriteHeader(401)
|
||||
@@ -100,7 +123,7 @@ func TestOIDCSessionLifecycle(t *testing.T) {
|
||||
u, _ := url.Parse(login.Header().Get("Location"))
|
||||
nonce = u.Query().Get("nonce")
|
||||
challenge = u.Query().Get("code_challenge")
|
||||
if u.Query().Get("code_challenge_method") != "S256" || nonce == "" {
|
||||
if u.Query().Get("code_challenge_method") != "S256" || nonce == "" || u.Query().Get("internal_sync") != "1" || u.Query().Has("prompt") || u.Query().Has("max_age") {
|
||||
t.Fatal("missing PKCE or nonce")
|
||||
}
|
||||
callback := httptest.NewRequest("GET", "/auth/callback?code=test&state="+u.Query().Get("state"), nil)
|
||||
@@ -112,11 +135,11 @@ func TestOIDCSessionLifecycle(t *testing.T) {
|
||||
}
|
||||
var sessionCookie *http.Cookie
|
||||
for _, c := range response.Result().Cookies() {
|
||||
if c.Name == "fb_session" {
|
||||
if c.Name == internalCookie {
|
||||
sessionCookie = c
|
||||
}
|
||||
}
|
||||
if sessionCookie == nil || !sessionCookie.HttpOnly {
|
||||
if sessionCookie == nil || !sessionCookie.HttpOnly || !sessionCookie.Secure || sessionCookie.Path != "/" || sessionCookie.Domain != "" || sessionCookie.SameSite != http.SameSiteLaxMode {
|
||||
t.Fatal("missing HttpOnly session")
|
||||
}
|
||||
request := func(method, path string) *httptest.ResponseRecorder {
|
||||
@@ -124,6 +147,7 @@ func TestOIDCSessionLifecycle(t *testing.T) {
|
||||
r.AddCookie(sessionCookie)
|
||||
if method == "POST" {
|
||||
r.Header.Set("X-FB-Request", "1")
|
||||
r.Header.Set("X-FB-Session-State", "state-1")
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
@@ -171,8 +195,8 @@ func TestOIDCSessionLifecycle(t *testing.T) {
|
||||
}
|
||||
roles = []string{"User"}
|
||||
check = request("GET", "/api/session")
|
||||
if check.Code != 200 || !strings.Contains(check.Body.String(), `"admin":true`) {
|
||||
t.Fatal("login role snapshot changed during local session")
|
||||
if check.Code != 200 || !strings.Contains(check.Body.String(), `"admin":false`) {
|
||||
t.Fatal("current roles were not refreshed")
|
||||
}
|
||||
|
||||
for _, p := range []string{"/api/login", "/api/signup", "/api/renew", "/api/command"} {
|
||||
@@ -200,13 +224,13 @@ func TestOIDCSessionLifecycle(t *testing.T) {
|
||||
h.ServeHTTP(login, httptest.NewRequest("GET", "/auth/login", nil))
|
||||
u, _ = url.Parse(login.Header().Get("Location"))
|
||||
nonce, challenge = u.Query().Get("nonce"), u.Query().Get("code_challenge")
|
||||
profileSubject = "another-subject"
|
||||
invalidNonce = true
|
||||
callback = httptest.NewRequest("GET", "/auth/callback?code=test&state="+u.Query().Get("state"), nil)
|
||||
callback.AddCookie(login.Result().Cookies()[0])
|
||||
w = httptest.NewRecorder()
|
||||
h.ServeHTTP(w, callback)
|
||||
if w.Code != 401 {
|
||||
t.Fatal("mismatched UserInfo subject accepted")
|
||||
t.Fatal("invalid nonce accepted")
|
||||
}
|
||||
// Expired/idle sessions are rejected, even with an otherwise valid cookie.
|
||||
restarted, err := NewSSO(context.Background(), st, &settings.Server{Root: root}, SSOConfig{Issuer: issuer, ClientID: "client", ClientSecret: "secret", PublicURL: "http://127.0.0.1:9111"})
|
||||
@@ -258,13 +282,4 @@ func TestOIDCSessionLifecycle(t *testing.T) {
|
||||
t.Fatalf("existing records changed: %d %v", len(all), err)
|
||||
}
|
||||
}
|
||||
sessionKey := sha256.Sum256([]byte(sessionCookie.Value))
|
||||
for _, tc := range []struct{ expires, touched time.Time }{{time.Now().Add(-time.Second), time.Now()}, {time.Now().Add(time.Hour), time.Now().Add(-31 * time.Minute)}} {
|
||||
s.mu.Lock()
|
||||
s.sessions[sessionKey] = &ssoSession{Identity: sessionIdentity{ID: 2, Name: "alice"}, Expires: tc.expires, Touched: tc.touched}
|
||||
s.mu.Unlock()
|
||||
if request("GET", "/api/session").Code != 401 {
|
||||
t.Fatal("expired/idle session accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
-2
@@ -9,6 +9,7 @@ import (
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
@@ -33,8 +34,10 @@ func handleWithStaticData(w http.ResponseWriter, _ *http.Request, d *data, fSys
|
||||
"Version": version.Version,
|
||||
"StaticURL": path.Join(d.server.BaseURL, "/static"),
|
||||
"Signup": false,
|
||||
"NoAuth": false,
|
||||
"NoAuth": d.server.NoSSO,
|
||||
"AuthMethod": "sso",
|
||||
"SSOIssuer": d.server.SSOIssuer,
|
||||
"SSOClientID": d.server.SSOClientID,
|
||||
"LogoutPage": "/auth/logout",
|
||||
"LoginPage": true,
|
||||
"ReCaptcha": false,
|
||||
@@ -52,6 +55,13 @@ func handleWithStaticData(w http.ResponseWriter, _ *http.Request, d *data, fSys
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
frameSource := ""
|
||||
if d.server.SSOIssuer != "" && !d.server.NoSSO {
|
||||
if issuer, e := url.Parse(d.server.SSOIssuer); e == nil {
|
||||
frameSource = " " + issuer.Scheme + "://" + issuer.Host
|
||||
}
|
||||
}
|
||||
data["FrameSource"] = frameSource
|
||||
data["Json"] = template.JS(strings.ReplaceAll(string(b), `'`, `\'`))
|
||||
|
||||
fileContents, err := fs.ReadFile(fSys, file)
|
||||
@@ -73,7 +83,7 @@ func handleWithStaticData(w http.ResponseWriter, _ *http.Request, d *data, fSys
|
||||
cached, _ = indexTemplates.LoadOrStore(contents, parsed)
|
||||
}
|
||||
index := cached.(*template.Template)
|
||||
w.Header().Set("Content-Security-Policy", fmt.Sprintf("default-src 'self'; script-src 'self' 'nonce-%s' 'strict-dynamic'; style-src 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' data: blob:; media-src 'self' blob:; manifest-src 'self' blob:; worker-src 'self' blob:; frame-src 'self' blob:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'", data["Nonce"]))
|
||||
w.Header().Set("Content-Security-Policy", fmt.Sprintf("default-src 'self'; script-src 'self' 'nonce-%s' 'strict-dynamic'; style-src 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' data: blob:; media-src 'self' blob:; manifest-src 'self' blob:; worker-src 'self' blob:; frame-src 'self' blob:%s; object-src 'none'; base-uri 'self'; frame-ancestors 'none'", data["Nonce"], frameSource))
|
||||
err = index.Execute(w, data)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
|
||||
@@ -66,14 +66,21 @@ func TestWorkspaceBrowserQA(t *testing.T) {
|
||||
}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r = authorizeTestRequest(r, testSession(1, "QA", true))
|
||||
if r.URL.Path == "/api/session" {
|
||||
if r.URL.Path == "/api/session" || r.URL.Path == "/auth/session" {
|
||||
u, err := st.Users.Get(root, false, uint(1))
|
||||
if err != nil {
|
||||
http.Error(w, "user", 500)
|
||||
return
|
||||
}
|
||||
u.DisplayName = "QA Account"
|
||||
renderJSON(w, r, ssoUserInfo(u))
|
||||
profile := ssoUserInfo(u)
|
||||
profile.SessionState = "qa"
|
||||
profile.AuthMode = "no-sso"
|
||||
if r.URL.Path == "/auth/session" {
|
||||
writeState(w, 200, browserState{Status: "authenticated", Authenticated: true, State: "qa", User: &profile})
|
||||
} else {
|
||||
renderJSON(w, r, profile)
|
||||
}
|
||||
return
|
||||
}
|
||||
handler.ServeHTTP(w, r)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
param([string]$Version = '3.1.0')
|
||||
param([string]$Version = '3.2.0')
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repo = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
|
||||
Push-Location $repo
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
VERSION="${VERSION:-3.1.0}"
|
||||
VERSION="${VERSION:-3.2.0}"
|
||||
COMMIT=$(git rev-parse --short HEAD)
|
||||
(cd frontend && pnpm install --frozen-lockfile && pnpm run build)
|
||||
mkdir -p build/release/linux-amd64
|
||||
|
||||
@@ -65,6 +65,9 @@ func (s *Settings) GetRules() []rules.Rule {
|
||||
// Server specific settings.
|
||||
type Server struct {
|
||||
AddonsPath string `json:"-"`
|
||||
NoSSO bool `json:"-"`
|
||||
SSOIssuer string `json:"-"`
|
||||
SSOClientID string `json:"-"`
|
||||
Root string `json:"root"`
|
||||
BaseURL string `json:"baseURL"`
|
||||
Socket string `json:"socket"`
|
||||
|
||||
Reference in new issue
Block a user