Compare commits
19
Commits
stable-8.2
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
456dc232cb | ||
|
|
b690f4eb8f | ||
|
|
455d76cab4 | ||
|
|
10247ace43 | ||
|
|
ce462dbe20 | ||
|
|
cf505b3065 | ||
|
|
f8d3daf7ff | ||
|
|
0b0d460eac | ||
|
|
3ac62eb510 | ||
|
|
fbe1b9560b | ||
|
|
019e65a951 | ||
|
|
8b132a520e | ||
|
|
de0eace537 | ||
|
|
a5f57a6e2a | ||
|
|
35b11ed975 | ||
|
|
a3c56a9272 | ||
|
|
d372a0f4c0 | ||
|
|
d466cb205c | ||
|
|
d76d421fc6 |
No files matched your search
-22
@@ -1,22 +0,0 @@
|
||||
---
|
||||
exclude_paths:
|
||||
- '.github/**'
|
||||
- 'CHANGELOG.md'
|
||||
- '**/CHANGELOG.md'
|
||||
- 'changelog/**'
|
||||
- '**/changelog/**'
|
||||
- 'docs/**'
|
||||
- '**/docs/**'
|
||||
- '**/pkg/proto/**'
|
||||
- 'idp/ui_config/**'
|
||||
- 'idp/scripts/**'
|
||||
- 'settings/rollup.config.js'
|
||||
- 'accounts/rollup.config.js'
|
||||
- 'deployments/**'
|
||||
- 'tests/acceptance/expected-failures-*.md'
|
||||
- 'tests/acceptance/bootstrap/**'
|
||||
- 'tests/acceptance/TestHelpers/**'
|
||||
- 'tests/acceptance/run.sh'
|
||||
- 'vendor/**/*'
|
||||
- 'tests/ociswrapper/vendor/**'
|
||||
...
|
||||
@@ -0,0 +1,99 @@
|
||||
name: Build Package (Reverse Cloud)
|
||||
|
||||
# 手動実行専用。ビルドして Actions の Artifact(7 日間)に保存する。
|
||||
# push / PR / タグでは実行しない。
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: 'パッケージのバージョン(空欄なら 0.0.0-dev.<短縮SHA>)'
|
||||
required: false
|
||||
default: ''
|
||||
|
||||
concurrency:
|
||||
group: build-package-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
NODE_VERSION: '24'
|
||||
CHROMEDRIVER_SKIP_DOWNLOAD: 'true'
|
||||
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: '1'
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 90
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Determine version
|
||||
id: ver
|
||||
shell: bash
|
||||
env:
|
||||
INPUT_VERSION: ${{ github.event.inputs.version }}
|
||||
run: |
|
||||
if [[ -n "${INPUT_VERSION}" ]]; then
|
||||
VERSION="${INPUT_VERSION#v}"
|
||||
else
|
||||
VERSION="0.0.0-dev.$(git rev-parse --short HEAD)"
|
||||
fi
|
||||
if ! [[ "${VERSION}" =~ ^[0-9A-Za-z.+-]+$ ]]; then
|
||||
echo "::error::invalid version: ${VERSION}"; exit 1
|
||||
fi
|
||||
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache-dependency-path: go.sum
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- name: Enable pnpm (packageManager in web/package.json)
|
||||
id: pnpm
|
||||
shell: bash
|
||||
run: |
|
||||
corepack enable
|
||||
cd web && corepack prepare --activate && pnpm --version
|
||||
echo "store=$(pnpm store path --silent)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Cache pnpm store
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ${{ steps.pnpm.outputs.store }}
|
||||
key: pnpm-${{ runner.os }}-${{ hashFiles('web/pnpm-lock.yaml', 'services/idp/pnpm-lock.yaml') }}
|
||||
restore-keys: pnpm-${{ runner.os }}-
|
||||
|
||||
- name: Build frontend assets (web / idp)
|
||||
run: make ci-node-generate
|
||||
|
||||
- name: Go generate
|
||||
env:
|
||||
BUF_TOKEN: ${{ secrets.BUF_API_TOKEN }}
|
||||
run: make ci-go-generate
|
||||
|
||||
- name: Build ocis (linux/amd64, static PIE)
|
||||
shell: bash
|
||||
env:
|
||||
CGO_ENABLED: '0'
|
||||
VERSION: ${{ steps.ver.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
sed -i "s/LatestTag = \".*\"/LatestTag = \"${VERSION}\"/" ocis-pkg/version/version.go
|
||||
make -C ocis release-linux-docker-amd64
|
||||
OUT="dist/ocis-${VERSION}-linux-amd64"
|
||||
mkdir -p dist
|
||||
cp ocis/dist/binaries/ocis-linux-amd64 "${OUT}"
|
||||
(cd dist && sha256sum "$(basename "${OUT}")" > "$(basename "${OUT}").sha256")
|
||||
ls -lh dist
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ocis-${{ steps.ver.outputs.version }}-linux-amd64
|
||||
path: dist/
|
||||
retention-days: 7
|
||||
@@ -1,3 +0,0 @@
|
||||
# Managed by owncloud/admin — edit codeowners/ownership.yml, not this file.
|
||||
# Generated by scripts/sync-codeowners.py. Last matching pattern wins.
|
||||
* @owncloud/ocis-maintainers
|
||||
@@ -1,15 +0,0 @@
|
||||
# Configuration for update-docs - https://github.com/behaviorbot/update-docs
|
||||
|
||||
# Comment to be posted to on PRs that don't update documentation
|
||||
updateDocsComment: >
|
||||
Thanks for opening this pull request! The maintainers of this repository would appreciate it if you would create a [changelog](https://github.com/owncloud/ocis/blob/master/changelog/README.md) item based on your changes.
|
||||
updateDocsWhiteList:
|
||||
- Tests-only
|
||||
- tests-only
|
||||
- Tests-Only
|
||||
- docs-only
|
||||
- docs-Only
|
||||
- Docs-Only
|
||||
|
||||
updateDocsTargetFiles:
|
||||
- changelog/unreleased/
|
||||
@@ -1,73 +0,0 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: gomod
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: sunday
|
||||
time: '22:00'
|
||||
timezone: Etc/UTC
|
||||
open-pull-requests-limit: 5
|
||||
groups:
|
||||
minor-and-patch:
|
||||
update-types:
|
||||
- minor
|
||||
- patch
|
||||
|
||||
- package-ecosystem: composer
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: sunday
|
||||
time: '22:00'
|
||||
timezone: Etc/UTC
|
||||
open-pull-requests-limit: 5
|
||||
groups:
|
||||
minor-and-patch:
|
||||
update-types:
|
||||
- minor
|
||||
- patch
|
||||
|
||||
- package-ecosystem: npm
|
||||
directory: "/services/idp"
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: sunday
|
||||
time: '22:00'
|
||||
timezone: Etc/UTC
|
||||
open-pull-requests-limit: 5
|
||||
groups:
|
||||
minor-and-patch:
|
||||
update-types:
|
||||
- minor
|
||||
- patch
|
||||
|
||||
- package-ecosystem: docker
|
||||
directories:
|
||||
- "/"
|
||||
- "/ocis/docker"
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: sunday
|
||||
time: '22:00'
|
||||
timezone: Etc/UTC
|
||||
open-pull-requests-limit: 5
|
||||
groups:
|
||||
minor-and-patch:
|
||||
update-types:
|
||||
- minor
|
||||
- patch
|
||||
|
||||
- package-ecosystem: github-actions
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: sunday
|
||||
time: '22:00'
|
||||
timezone: Etc/UTC
|
||||
open-pull-requests-limit: 5
|
||||
groups:
|
||||
minor-and-patch:
|
||||
update-types:
|
||||
- minor
|
||||
- patch
|
||||
@@ -1,82 +0,0 @@
|
||||
### Template
|
||||
[Release Template](https://github.com/owncloud/ocis/blob/master/.github/release_template.md)
|
||||
|
||||
### Prerequisites
|
||||
|
||||
* [ ] DEV/QA: Kickoff meeting [Kickoff meeting] (https://confluence.owncloud.com/display/QA/Technical+release+3.0.0+Overview)
|
||||
* [ ] DEV/QA: Define client versions and provide list of breaking changes for desktop/mobile team
|
||||
* [ ] DEV/QA: Check new strings and align with clients
|
||||
* [ ] DEV/DOCS: Create list of pending docs tasks
|
||||
* [ ] DEV: Create branch `release-x.x.x-rc.x` -> CODEFREEZE
|
||||
* [ ] DEV: bump ocis version in necessary files
|
||||
* [ ] DEV: `changelog/CHANGELOG.tmpl`
|
||||
* [ ] DEV: `ocis-pkg/version/version.go`
|
||||
* [ ] DEV: `sonar-project.properties`
|
||||
* [ ] DEV: prepare changelog folder in `changelog/x.x.x_????_??_??`
|
||||
* [ ] DEV: Check successful CI run on release branch
|
||||
* [ ] DEV: Create signed tag `vx.y.z-rc.x`
|
||||
* [ ] DEV: Check successful CI run on `vx.y.z-rc.x` tag / BLOCKING for all further activity
|
||||
* [ ] DEV: Merge back release branch
|
||||
* [ ] DEV: bump released deployments to `vx.y.z-rc.x`
|
||||
* [ ] DEV: update `ocis.released.owncloud.works`
|
||||
* [ ] DEV: https://ocis.team.owncloud.works/
|
||||
* [ ] DEV: needs snapshot and migration
|
||||
|
||||
### QA Phase
|
||||
|
||||
* [ ] QA: Confirmatory testing (if needed)
|
||||
* [ ] QA: [Compatibility test](https://github.com/owncloud/QA/blob/master/Server/Test_Plan_OCIS_Compatibility_Test.md)
|
||||
* [ ] QA: [Performance test](https://github.com/owncloud/cdperf/tree/main/packages/k6-tests/src)
|
||||
* [ ] QA: Documentation test:
|
||||
* [ ] QA: Single binary - setup
|
||||
* [ ] QA: Docker - setup
|
||||
* [ ] QA: Docker-compose - setup
|
||||
* [ ] QA: helm/k8s - setup
|
||||
* [ ] QA: e2e with different deployment:
|
||||
* [ ] QA: [wopi](ocis.ocis-wopi.released.owncloud.works)
|
||||
* [ ] QA: [traefik](ocis.ocis-traefik.released.owncloud.works)
|
||||
* [ ] QA: [ldap](ocis.ocis-ldap.released.owncloud.works)
|
||||
* [ ] QA: e2e with different storage:
|
||||
* [ ] QA: local
|
||||
* [ ] QA: nfs
|
||||
* [ ] QA: s3
|
||||
* [ ] QA: Different clients:
|
||||
* [ ] QA: desktop (define version) https://github.com/owncloud/client/releases
|
||||
* [ ] QA: against mac - smoke test
|
||||
* [ ] QA: against windows - smoke test
|
||||
* [ ] QA: against linux (use auto tests)
|
||||
* [ ] QA: android (define version) https://github.com/owncloud/android/releases
|
||||
* [ ] QA: ios (define version)
|
||||
* [ ] QA: [Web Office Smoke test](https://github.com/owncloud/QA/blob/master/Server/Test_Plan_OCIS_Smoke_Web_Office_Test.md) on Web Office (Collabora, Onlyoffice, Microsoft office)
|
||||
* [ ] QA: [Smoke test](https://github.com/owncloud/QA/blob/master/Server/Test_Plan_OCIS_Smoke_Test.md) on pre-production server
|
||||
* [ ] QA: [Smoke test](https://github.com/owncloud/QA/blob/master/Server/Test_Plan_OCIS_Smoke_Ldap_Test.md) ldap
|
||||
* [ ] QA: Collecting errors found
|
||||
|
||||
### After QA Phase
|
||||
|
||||
* [ ] Brief company-wide heads up via mail @tbsbdr
|
||||
* [ ] Create list of changed ENV vars and send to release-coordination@owncloud.com
|
||||
* [ ] Variable Name
|
||||
* [ ] Introduced in version
|
||||
* [ ] Default Value
|
||||
* [ ] Description
|
||||
* [ ] dependencies with user other components
|
||||
* [ ] DEV: Create branch `release-x.x.x`
|
||||
* [ ] DEV: bump ocis version in necessary files
|
||||
* [ ] DEV: `ocis-pkg/version/version.go`
|
||||
* [ ] DEV: `sonar-project.properties`
|
||||
* [ ] DEV: released deployment versions
|
||||
* [ ] DEV: prepare changelog folder in `changelog/x.x.x_???`
|
||||
* [ ] Release Notes + Breaking Changes @tbsbdr
|
||||
* [ ] Migration + Breaking Changes Admin Doc @mmattel
|
||||
* [ ] DEV: Create final signed tag
|
||||
* [ ] DEV: Check successful CI run on `vx.y.z` tag / BLOCKING for all further activity
|
||||
* [ ] Merge release notes
|
||||
|
||||
### Post-release communication
|
||||
* [ ] DEV: Create a `docs-stable-x.y` branch based on the docs folder in the ocis repo @micbar
|
||||
* [ ] DEV/QA: Ping documentation in RC about the new release tag (for ocis/helm chart version bump in docs)
|
||||
* [ ] DEV/QA: Ping marketing to update all download links (download mirrors are updated at the full hour, wait with ping until download is actually available)
|
||||
* [ ] DEV/QA: Ping @hodyroff once the demo instances are running this release
|
||||
* [ ] DEV: Merge back release branch
|
||||
* [ ] DEV: Create stable-x.y branch in the ocis repo from final tag
|
||||
@@ -1,88 +0,0 @@
|
||||
---
|
||||
_extends: gh-labels
|
||||
|
||||
repository:
|
||||
name: ocis
|
||||
description: ':atom_symbol: ownCloud Infinite Scale Stack'
|
||||
homepage: 'https://doc.owncloud.com/ocis/next/'
|
||||
topics: reva, ocis
|
||||
|
||||
private: false
|
||||
has_issues: true
|
||||
has_projects: true
|
||||
has_wiki: false
|
||||
has_downloads: false
|
||||
|
||||
default_branch: master
|
||||
|
||||
allow_squash_merge: true
|
||||
allow_merge_commit: true
|
||||
allow_rebase_merge: true
|
||||
|
||||
labels:
|
||||
- name: OCIS-Fastlane
|
||||
color: "#deadbf"
|
||||
description: Planned outside of the sprint
|
||||
- name: Storage:EOS
|
||||
color: "#3F7A62"
|
||||
- name: Storage:S3NG
|
||||
color: "#3F7A62"
|
||||
- name: Storage:CephFS
|
||||
color: "#3F7A62"
|
||||
- name: Storage:OCIS
|
||||
color: "#3F7A62"
|
||||
- name: Storage:POSIX
|
||||
color: "#3F7A62"
|
||||
- name: Storage:ownCloudSQL
|
||||
color: "#3F7A62"
|
||||
|
||||
teams:
|
||||
- name: ci
|
||||
permission: admin
|
||||
- name: employees
|
||||
permission: push
|
||||
- name: cern
|
||||
permission: triage
|
||||
- name: ocis-contractors
|
||||
permission: push
|
||||
|
||||
branches:
|
||||
- name: master
|
||||
protection:
|
||||
required_pull_request_reviews:
|
||||
required_approving_review_count: 1
|
||||
dismiss_stale_reviews: false
|
||||
require_code_owner_reviews: false
|
||||
required_status_checks:
|
||||
strict: false
|
||||
contexts: []
|
||||
enforce_admins: null
|
||||
restrictions:
|
||||
apps: []
|
||||
users:
|
||||
- dependabot
|
||||
teams:
|
||||
- ci
|
||||
- employees
|
||||
- ocis-contractors
|
||||
- name: stable-*
|
||||
protection:
|
||||
required_pull_request_reviews:
|
||||
required_approving_review_count: 2
|
||||
dismiss_stale_reviews: false
|
||||
require_code_owner_reviews: false
|
||||
required_status_checks:
|
||||
strict: false
|
||||
contexts: []
|
||||
enforce_admins: null
|
||||
restrictions:
|
||||
apps: []
|
||||
users:
|
||||
- dependabot
|
||||
teams:
|
||||
- ci
|
||||
- employees
|
||||
- ocis-contractors
|
||||
|
||||
...
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
only: issues
|
||||
# Number of days of inactivity before an issue becomes stale
|
||||
daysUntilStale: 60
|
||||
# Number of days of inactivity before a stale issue is closed
|
||||
daysUntilClose: 10
|
||||
# Issues with these labels will never be considered stale
|
||||
exemptLabels:
|
||||
- "Type:Bug"
|
||||
- "Type:Technical-Debt"
|
||||
- "Category:Enhancement"
|
||||
- "Category:Research"
|
||||
- "QA:team"
|
||||
# Label to use when marking an issue as stale
|
||||
staleLabel: "Status:Stale"
|
||||
# Comment to post when marking an issue as stale. Set to `false` to disable
|
||||
markComment: >
|
||||
This issue has been automatically marked as stale because it has not had
|
||||
recent activity. It will be closed in 10 days if no further activity occurs. Thank you
|
||||
for your contributions.
|
||||
# Comment to post when closing a stale issue. Set to `false` to disable
|
||||
closeComment: false
|
||||
@@ -1,809 +0,0 @@
|
||||
name: Acceptance Tests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
detect-changes:
|
||||
name: detect-changes
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
docs-only: ${{ steps.check.outputs.docs-only }}
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Check if changes are docs-only
|
||||
id: check
|
||||
run: |
|
||||
# Always run full CI on workflow_dispatch, tags, or when PR title contains [full-ci]
|
||||
if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
|
||||
echo "docs-only=false" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
PR_TITLE="${{ github.event.pull_request.title }}"
|
||||
if echo "$PR_TITLE" | grep -qi "\[full-ci\]"; then
|
||||
echo "docs-only=false" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Get changed files between the PR base and head
|
||||
CHANGED_FILES=$(git diff --name-only "${{ github.event.pull_request.base.sha }}" "${{ github.sha }}" 2>/dev/null || git diff --name-only HEAD~1)
|
||||
|
||||
# Patterns that are considered documentation/non-code changes
|
||||
DOCS_ONLY=true
|
||||
while IFS= read -r file; do
|
||||
case "$file" in
|
||||
.github/workflows/*) DOCS_ONLY=false; break ;;
|
||||
.github/*|.vscode/*|changelog/*|docs/*|deployments/*) ;;
|
||||
*/CHANGELOG.md|*/CONTRIBUTING.md|*/README.md|CHANGELOG.md|CONTRIBUTING.md|LICENSE|README.md) ;;
|
||||
*) DOCS_ONLY=false; break ;;
|
||||
esac
|
||||
done <<< "$CHANGED_FILES"
|
||||
|
||||
echo "docs-only=$DOCS_ONLY" >> "$GITHUB_OUTPUT"
|
||||
echo "Changed files docs-only: $DOCS_ONLY"
|
||||
|
||||
build-and-test:
|
||||
name: build-and-test
|
||||
needs: [detect-changes]
|
||||
if: needs.detect-changes.outputs.docs-only != 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
node-version: "24"
|
||||
|
||||
- name: Enable pnpm
|
||||
run: corepack enable && corepack prepare pnpm@10.33.3 --activate
|
||||
|
||||
- uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2
|
||||
with:
|
||||
php-version: "8.4"
|
||||
extensions: curl, xml, mbstring, zip, ldap, gd
|
||||
tools: composer
|
||||
|
||||
- name: Install libvips-dev for ENABLE_VIPS build
|
||||
run: |
|
||||
sudo apt-get update -qq
|
||||
# NEEDRESTART_MODE=a: auto-restart services silently; without this, needrestart can fail with exit code 6
|
||||
sudo NEEDRESTART_MODE=a apt-get install -y libvips-dev
|
||||
|
||||
- name: Pre-checks and generate
|
||||
run: |
|
||||
# Phase 1 — I/O + light CPU, no contention between tasks.
|
||||
# wa (I/O wait) will spike during npm/pnpm downloads.
|
||||
# Expected avg load: ~50-60 % CPU on 2 vCPU.
|
||||
vmstat 2 > /tmp/vmstat-phase1.log & MONITOR_PID=$!
|
||||
|
||||
(make vendor-bin-codestyle && make vendor-bin-codesniffer && make test-php-style && make check-env-var-annotations) > /tmp/php-style.log 2>&1 & PIDS=($!)
|
||||
(npm install -g @gherlint/gherlint@1.1.0 && make test-gherkin-lint) > /tmp/gherkin.log 2>&1 & PIDS+=($!)
|
||||
bash tests/acceptance/check-deleted-suites-in-expected-failure.sh > /tmp/suites.log 2>&1 & PIDS+=($!)
|
||||
make govulncheck > /tmp/govulncheck.log 2>&1 & PIDS+=($!)
|
||||
make ci-node-generate > /tmp/node-gen.log 2>&1 & PIDS+=($!)
|
||||
make ci-go-generate > /tmp/go-gen.log 2>&1 & PIDS+=($!)
|
||||
make changelog-lint > /tmp/changelog-lint.log 2>&1 & PIDS+=($!)
|
||||
|
||||
FAILED=0
|
||||
for PID in "${PIDS[@]}"; do wait "$PID" || FAILED=1; done
|
||||
kill $MONITOR_PID 2>/dev/null; wait $MONITOR_PID 2>/dev/null || true
|
||||
|
||||
# How to read the load line:
|
||||
# busy — % of time CPUs were doing work (100% = fully saturated)
|
||||
# runq — processes waiting for a CPU turn; runq >> nCPU means tasks
|
||||
# compete and each runs slower (runq 10 on 2 vCPU = ~5× slower)
|
||||
# wa — % waiting on disk/network; wa > 20% = I/O bound, not CPU bound
|
||||
# → high wa: add more parallel tasks; high runq: reduce them
|
||||
awk '/^[ ]*[0-9]/ { busy=100-$15; sum_b+=busy; if(busy>pk_b)pk_b=busy;
|
||||
sum_r+=$1; if($1>pk_r) pk_r=$1; sum_wa+=$16; n++ }
|
||||
END { printf "=== phase 1 load (2 vCPU): avg busy %d%% peak %d%% | avg runq %.0f peak %d | avg wa %d%%\n",
|
||||
sum_b/n, pk_b, sum_r/n, pk_r, sum_wa/n }' /tmp/vmstat-phase1.log
|
||||
|
||||
echo "=== php-style ===" && cat /tmp/php-style.log
|
||||
echo "=== gherkin ===" && cat /tmp/gherkin.log
|
||||
echo "=== suites ===" && cat /tmp/suites.log
|
||||
echo "=== govulncheck ===" && cat /tmp/govulncheck.log
|
||||
echo "=== ci-node-generate ===" && cat /tmp/node-gen.log
|
||||
echo "=== ci-go-generate ===" && cat /tmp/go-gen.log
|
||||
echo "=== changelog-lint ===" && cat /tmp/changelog-lint.log
|
||||
|
||||
exit $FAILED
|
||||
|
||||
- name: Trivy scan
|
||||
uses: aquasecurity/trivy-action@57a97c7e7821a5776cebc9bb87c984fa69cba8f1 # v0.35.0
|
||||
with:
|
||||
scan-type: fs
|
||||
format: table
|
||||
exit-code: 1
|
||||
severity: CRITICAL,HIGH
|
||||
trivy-config: .trivy.yaml
|
||||
|
||||
- name: Build, lint and test
|
||||
run: |
|
||||
# Phase 2 — all three are CPU-bound Go compilation on 2 vCPU.
|
||||
# They compete for CPU (expect id < 10, load ~95 %) but share the
|
||||
# Go build cache within this runner, so make test reuses artifacts
|
||||
# from the ocis build. Critical path = ocis build (~300 s).
|
||||
vmstat 2 > /tmp/vmstat-phase2.log & MONITOR_PID=$!
|
||||
|
||||
make ci-golangci-lint > /tmp/golangci-lint.log 2>&1 & PIDS=($!)
|
||||
ENABLE_VIPS=true make -C ocis build > /tmp/ocis-build.log 2>&1 & PIDS+=($!)
|
||||
make test > /tmp/unit-tests.log 2>&1 & PIDS+=($!)
|
||||
GOWORK=off make -C tests/ociswrapper build > /tmp/ociswrapper-build.log 2>&1 & PIDS+=($!)
|
||||
|
||||
FAILED=0
|
||||
for PID in "${PIDS[@]}"; do wait "$PID" || FAILED=1; done
|
||||
kill $MONITOR_PID 2>/dev/null; wait $MONITOR_PID 2>/dev/null || true
|
||||
|
||||
# Signal: busy=saturated runq>>2=tasks competing(slows each) wa>20%=I/O bound
|
||||
awk '/^[ ]*[0-9]/ { busy=100-$15; sum_b+=busy; if(busy>pk_b)pk_b=busy;
|
||||
sum_r+=$1; if($1>pk_r) pk_r=$1; sum_wa+=$16; n++ }
|
||||
END { printf "=== phase 2 load (2 vCPU): avg busy %d%% peak %d%% | avg runq %.0f peak %d | avg wa %d%%\n",
|
||||
sum_b/n, pk_b, sum_r/n, pk_r, sum_wa/n }' /tmp/vmstat-phase2.log
|
||||
|
||||
echo "=== golangci-lint ===" && cat /tmp/golangci-lint.log
|
||||
echo "=== ocis build ===" && cat /tmp/ocis-build.log
|
||||
echo "=== ociswrapper build ===" && cat /tmp/ociswrapper-build.log
|
||||
echo "=== unit tests ===" && cat /tmp/unit-tests.log
|
||||
|
||||
exit $FAILED
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
path: |
|
||||
ocis/bin/ocis
|
||||
tests/ociswrapper/bin/ociswrapper
|
||||
retention-days: 1
|
||||
if-no-files-found: error
|
||||
|
||||
local-api-tests:
|
||||
name: ${{ matrix.suite }}
|
||||
needs: [build-and-test]
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
suite:
|
||||
# contract & locks
|
||||
- apiContract
|
||||
- apiLocks
|
||||
# settings & notifications (needs email)
|
||||
- apiSettings
|
||||
- apiNotification
|
||||
- apiCors
|
||||
# graph
|
||||
- apiGraphUser
|
||||
- apiGraph
|
||||
- apiGraphGroup
|
||||
# spaces & dav
|
||||
- apiSpaces
|
||||
- apiSpacesShares
|
||||
- apiSpacesDavOperation
|
||||
- apiDownloads
|
||||
- apiAsyncUpload
|
||||
- apiDepthInfinity
|
||||
- apiArchiver
|
||||
- apiActivities
|
||||
# search
|
||||
- apiSearch1
|
||||
- apiSearch2
|
||||
- apiSearchContent # needs Tika
|
||||
# sharing
|
||||
- apiSharingNgShares
|
||||
- apiReshare
|
||||
- apiSharingNgPermissions
|
||||
- apiSharingNgAdditionalShareRole
|
||||
- apiSharingNgDriveInvitation
|
||||
- apiSharingNgItemInvitation
|
||||
- apiSharingNgDriveLinkShare
|
||||
- apiSharingNgItemLinkShare
|
||||
- apiSharingNgLinkShareManagement
|
||||
# auth
|
||||
- apiAuthApp
|
||||
# antivirus (needs ClamAV)
|
||||
- apiAntivirus
|
||||
# federation (needs email + federation ocis)
|
||||
- apiOcm
|
||||
# collaboration (needs WOPI)
|
||||
- apiCollaboration
|
||||
- apiVault
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
|
||||
- uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2
|
||||
with:
|
||||
php-version: "8.4"
|
||||
extensions: curl, xml, mbstring, zip, ldap, gd
|
||||
tools: composer
|
||||
|
||||
- name: Cache libcurl 8.12.0
|
||||
id: cache-libcurl
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: /opt/libcurl
|
||||
key: libcurl-8.12.0-${{ runner.os }}
|
||||
|
||||
- name: Install libcurl 8.12.0 build dependencies
|
||||
# Always run: libvips-dev is needed at runtime (govips thumbnails in the pre-built binary)
|
||||
run: |
|
||||
sudo apt-get update -qq
|
||||
# NEEDRESTART_MODE=a: auto-restart services silently; without this, needrestart can fail with exit code 6
|
||||
sudo NEEDRESTART_MODE=a apt-get install -y libssl-dev libnghttp2-dev libpsl-dev libldap-dev libssh-dev zlib1g-dev libvips-dev
|
||||
|
||||
- name: Compile libcurl 8.12.0 from source
|
||||
if: steps.cache-libcurl.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
cd /tmp
|
||||
curl -sLO https://curl.se/download/curl-8.12.0.tar.gz
|
||||
tar xzf curl-8.12.0.tar.gz
|
||||
cd curl-8.12.0
|
||||
./configure --with-ssl --with-zlib --with-nghttp2 --prefix=/opt/libcurl --enable-versioned-symbols --silent
|
||||
make -j$(nproc) --silent
|
||||
sudo make install --silent
|
||||
|
||||
- name: Restore libcurl ldconfig
|
||||
# Always run: on cache hit the .so files are restored to /opt/libcurl/lib but
|
||||
# /etc/ld.so.cache on the fresh runner doesn't know about them yet.
|
||||
# Without ldconfig, PHP's curl extension can't find libcurl even though it's present.
|
||||
run: |
|
||||
echo "/opt/libcurl/lib" | sudo tee /etc/ld.so.conf.d/libcurl-8.conf
|
||||
sudo ldconfig
|
||||
/opt/libcurl/bin/curl --version | head -1
|
||||
php -r '
|
||||
$v = curl_version()["version"];
|
||||
echo "PHP curl: $v\n";
|
||||
if (version_compare($v, "8.12.0", "<")) {
|
||||
fwrite(STDERR, "FATAL: PHP sees libcurl $v, need >= 8.12.0\n");
|
||||
exit(1);
|
||||
}
|
||||
'
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
- name: Restore binary permissions
|
||||
run: chmod +x ocis/bin/ocis tests/ociswrapper/bin/ociswrapper
|
||||
|
||||
- name: Run ${{ matrix.suite }}
|
||||
run: BEHAT_SUITES=${{ matrix.suite }} python3 tests/acceptance/run-github.py
|
||||
|
||||
cli-tests:
|
||||
needs: [build-and-test]
|
||||
name: ${{ matrix.suite }}
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
suite:
|
||||
- cliCommands,apiServiceAvailability # grouped: both need ClamAV + email services
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
|
||||
- uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2
|
||||
with:
|
||||
php-version: "8.4"
|
||||
extensions: curl, xml, mbstring, zip, ldap, gd
|
||||
tools: composer
|
||||
|
||||
- name: Install libvips runtime
|
||||
run: |
|
||||
sudo apt-get update -qq
|
||||
# NEEDRESTART_MODE=a: auto-restart services silently; without this, needrestart can fail with exit code 6
|
||||
sudo NEEDRESTART_MODE=a apt-get install -y libvips42t64
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
- name: Restore binary permissions
|
||||
run: chmod +x ocis/bin/ocis tests/ociswrapper/bin/ociswrapper
|
||||
|
||||
- name: Run ${{ matrix.suite }}
|
||||
run: BEHAT_SUITES="${{ matrix.suite }}" python3 tests/acceptance/run-github.py
|
||||
|
||||
ldap-pool-tests:
|
||||
needs: [build-and-test]
|
||||
name: ldapPool-${{ matrix.suite }}
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
suite:
|
||||
- apiGraphUser,apiGraph,apiGraphGroup
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
|
||||
- uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2
|
||||
with:
|
||||
php-version: "8.4"
|
||||
extensions: curl, xml, mbstring, zip, ldap, gd
|
||||
tools: composer
|
||||
|
||||
- name: Install libvips runtime
|
||||
run: |
|
||||
sudo apt-get update -qq
|
||||
# NEEDRESTART_MODE=a: auto-restart services silently; without this, needrestart can fail with exit code 6
|
||||
sudo NEEDRESTART_MODE=a apt-get install -y libvips42t64
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
- name: Restore binary permissions
|
||||
run: chmod +x ocis/bin/ocis tests/ociswrapper/bin/ociswrapper
|
||||
|
||||
- name: Run ${{ matrix.suite }} with OCIS_LDAP_POOL_ENABLED=true
|
||||
run: BEHAT_SUITES="${{ matrix.suite }}" OCIS_LDAP_POOL_ENABLED=true python3 tests/acceptance/run-github.py
|
||||
|
||||
core-api-tests:
|
||||
name: ${{ matrix.suite }}
|
||||
needs: [build-and-test]
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
suite:
|
||||
- "coreApiAuth,coreApiCapabilities,coreApiFavorites,coreApiMain,coreApiVersions"
|
||||
- "coreApiShareManagementBasicToShares,coreApiShareManagementToShares"
|
||||
- "coreApiSharees"
|
||||
- "coreApiSharePublicLink2"
|
||||
- "coreApiShareOperationsToShares1,coreApiShareOperationsToShares2,coreApiSharePublicLink1,coreApiShareCreateSpecialToShares1,coreApiShareCreateSpecialToShares2,coreApiShareUpdateToShares"
|
||||
- "coreApiTrashbin,coreApiTrashbinRestore,coreApiWebdavEtagPropagation1,coreApiWebdavEtagPropagation2"
|
||||
- "coreApiWebdavDelete,coreApiWebdavOperations,coreApiWebdavMove2"
|
||||
- "coreApiWebdavProperties"
|
||||
- "coreApiWebdavMove1,coreApiWebdavPreviews,coreApiWebdavUpload,coreApiWebdavUploadTUS"
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
|
||||
- uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2
|
||||
with:
|
||||
php-version: "8.4"
|
||||
extensions: curl, xml, mbstring, zip, ldap, gd
|
||||
tools: composer
|
||||
|
||||
- name: Cache libcurl 8.12.0
|
||||
id: cache-libcurl
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: /opt/libcurl
|
||||
key: libcurl-8.12.0-${{ runner.os }}
|
||||
|
||||
- name: Install libcurl 8.12.0 build dependencies
|
||||
# Always run: libvips-dev is needed at runtime (govips thumbnails in the pre-built binary)
|
||||
run: |
|
||||
sudo apt-get update -qq
|
||||
# NEEDRESTART_MODE=a: auto-restart services silently; without this, needrestart can fail with exit code 6
|
||||
sudo NEEDRESTART_MODE=a apt-get install -y libssl-dev libnghttp2-dev libpsl-dev libldap-dev libssh-dev zlib1g-dev libvips-dev
|
||||
|
||||
- name: Compile libcurl 8.12.0 from source
|
||||
if: steps.cache-libcurl.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
cd /tmp
|
||||
curl -sLO https://curl.se/download/curl-8.12.0.tar.gz
|
||||
tar xzf curl-8.12.0.tar.gz
|
||||
cd curl-8.12.0
|
||||
./configure --with-ssl --with-zlib --with-nghttp2 --prefix=/opt/libcurl --enable-versioned-symbols --silent
|
||||
make -j$(nproc) --silent
|
||||
sudo make install --silent
|
||||
|
||||
- name: Restore libcurl ldconfig
|
||||
# Always run: on cache hit the .so files are restored to /opt/libcurl/lib but
|
||||
# /etc/ld.so.cache on the fresh runner doesn't know about them yet.
|
||||
# Without ldconfig, PHP's curl extension can't find libcurl even though it's present.
|
||||
run: |
|
||||
echo "/opt/libcurl/lib" | sudo tee /etc/ld.so.conf.d/libcurl-8.conf
|
||||
sudo ldconfig
|
||||
/opt/libcurl/bin/curl --version | head -1
|
||||
php -r '
|
||||
$v = curl_version()["version"];
|
||||
echo "PHP curl: $v\n";
|
||||
if (version_compare($v, "8.12.0", "<")) {
|
||||
fwrite(STDERR, "FATAL: PHP sees libcurl $v, need >= 8.12.0\n");
|
||||
exit(1);
|
||||
}
|
||||
'
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
- name: Restore binary permissions
|
||||
run: chmod +x ocis/bin/ocis tests/ociswrapper/bin/ociswrapper
|
||||
|
||||
- name: Run ${{ matrix.suite }}
|
||||
run: >
|
||||
BEHAT_SUITES="${{ matrix.suite }}"
|
||||
ACCEPTANCE_TEST_TYPE=core-api
|
||||
WITH_REMOTE_PHP=true
|
||||
python3 tests/acceptance/run-github.py
|
||||
|
||||
e2e-tests:
|
||||
name: e2e-${{ matrix.suite }}
|
||||
needs: [build-and-test]
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- suite: part-1
|
||||
args: "--type playwright --total-parts 4 --xsuites search,app-provider,ocm,keycloak,mfa,oidc --run-part 1"
|
||||
- suite: part-2
|
||||
args: "--type playwright --total-parts 4 --xsuites search,app-provider,ocm,keycloak,mfa,oidc --run-part 2"
|
||||
- suite: part-3
|
||||
args: "--type playwright --total-parts 4 --xsuites search,app-provider,ocm,keycloak,mfa,oidc --run-part 3"
|
||||
- suite: part-4
|
||||
args: "--type playwright --total-parts 4 --xsuites search,app-provider,ocm,keycloak,mfa,oidc --run-part 4"
|
||||
- suite: search
|
||||
args: "--type playwright --suites search"
|
||||
tika: true
|
||||
- suite: keycloak
|
||||
args: "--type playwright --suites journeys,keycloak"
|
||||
keycloak: true
|
||||
- suite: mfa
|
||||
args: "--type playwright --suites mfa"
|
||||
mfa: true
|
||||
- suite: oidc
|
||||
args: "--type playwright specs/oidc/refreshToken.spec.ts"
|
||||
oidc: true
|
||||
- suite: oidc-iframe
|
||||
args: "--type playwright specs/oidc/iframeTokenRenewal.spec.ts"
|
||||
oidc_iframe: true
|
||||
- suite: app-provider
|
||||
args: "--type playwright --suites app-provider"
|
||||
collaboration: true
|
||||
- suite: ocm
|
||||
args: "--type playwright --suites ocm"
|
||||
federated: true
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
# 24.16.0 breaks playwright install (yauzl zip extraction hangs); pin to last known good.
|
||||
# https://github.com/microsoft/playwright/issues/40724
|
||||
node-version: "24.15.0"
|
||||
- name: Enable pnpm
|
||||
run: |
|
||||
corepack enable && corepack prepare pnpm@10.33.3 --activate
|
||||
pnpm config set store-dir ./.pnpm-store
|
||||
|
||||
- name: Install libvips runtime
|
||||
run: |
|
||||
sudo apt-get update -qq
|
||||
# NEEDRESTART_MODE=a: auto-restart services silently; without this, needrestart can fail with exit code 6
|
||||
sudo NEEDRESTART_MODE=a apt-get install -y libvips42t64
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
- name: Restore binary permissions
|
||||
run: chmod +x ocis/bin/ocis tests/ociswrapper/bin/ociswrapper
|
||||
|
||||
- name: Cache Playwright Chromium
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: playwright-chromium-${{ hashFiles('web/pnpm-lock.yaml') }}
|
||||
|
||||
# --- Tika (search suite only) ---
|
||||
- name: Start Tika
|
||||
if: matrix.tika == true
|
||||
run: |
|
||||
docker run -d --name tika --network host apache/tika:3.2.2.0-full
|
||||
timeout 120 bash -c 'until curl -sf http://localhost:9998; do sleep 2; done'
|
||||
echo "tika ready."
|
||||
|
||||
# --- Keycloak (keycloak and mfa suites) ---
|
||||
- name: Generate Keycloak certs
|
||||
if: matrix.keycloak == true || matrix.mfa == true
|
||||
run: |
|
||||
mkdir -p keycloak-certs
|
||||
openssl req -x509 -newkey rsa:2048 \
|
||||
-keyout keycloak-certs/keycloakkey.pem \
|
||||
-out keycloak-certs/keycloakcrt.pem \
|
||||
-nodes -days 365 -subj '/CN=keycloak' \
|
||||
-addext 'subjectAltName=DNS:localhost,IP:127.0.0.1'
|
||||
chmod -R 777 keycloak-certs
|
||||
|
||||
- name: Start Postgres
|
||||
if: matrix.keycloak == true || matrix.mfa == true
|
||||
run: |
|
||||
docker run -d --name postgres --network host \
|
||||
-e POSTGRES_DB=keycloak \
|
||||
-e POSTGRES_USER=keycloak \
|
||||
-e POSTGRES_PASSWORD=keycloak \
|
||||
postgres:alpine3.18
|
||||
timeout 30 bash -c 'until docker exec postgres pg_isready -U keycloak; do sleep 1; done'
|
||||
|
||||
- name: Start Keycloak
|
||||
if: matrix.keycloak == true || matrix.mfa == true
|
||||
run: |
|
||||
# The mfa suite needs a different realm with TOTP MFA configured.
|
||||
# ocis-ci-realm uses ocis-server:9200, ocis-mfa-ci-realm uses localhost:9200;
|
||||
# ocis runs on 127.0.0.1:9200 so we rewrite both forms.
|
||||
if [[ "${{ matrix.mfa }}" == "true" ]]; then
|
||||
REALM_FILE=tests/config/ci/ocis-mfa-ci-realm.dist.json
|
||||
else
|
||||
REALM_FILE=tests/config/ci/ocis-ci-realm.dist.json
|
||||
fi
|
||||
sed -e 's|https://ocis-server:9200|https://127.0.0.1:9200|g' \
|
||||
-e 's|https://localhost:9200|https://127.0.0.1:9200|g' \
|
||||
"$REALM_FILE" > /tmp/ocis-realm.json
|
||||
docker run -d --name keycloak --network host \
|
||||
-e OCIS_DOMAIN=https://127.0.0.1:9200 \
|
||||
-e KC_HOSTNAME=localhost \
|
||||
-e KC_PORT=8443 \
|
||||
-e KC_DB=postgres \
|
||||
-e "KC_DB_URL=jdbc:postgresql://localhost:5432/keycloak" \
|
||||
-e KC_DB_USERNAME=keycloak \
|
||||
-e KC_DB_PASSWORD=keycloak \
|
||||
-e KC_FEATURES=impersonation \
|
||||
-e KC_BOOTSTRAP_ADMIN_USERNAME=admin \
|
||||
-e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \
|
||||
-e KC_HTTPS_CERTIFICATE_FILE=/keycloak-certs/keycloakcrt.pem \
|
||||
-e KC_HTTPS_CERTIFICATE_KEY_FILE=/keycloak-certs/keycloakkey.pem \
|
||||
-v "$(pwd)/keycloak-certs:/keycloak-certs:ro" \
|
||||
-v "/tmp/ocis-realm.json:/opt/keycloak/data/import/oCIS-realm.json:ro" \
|
||||
quay.io/keycloak/keycloak:26.2.5 \
|
||||
start-dev --proxy-headers xforwarded \
|
||||
--spi-connections-http-client-default-disable-trust-manager=true \
|
||||
--import-realm --health-enabled=true
|
||||
timeout 300 bash -c 'until curl -skf https://localhost:9000/health/ready; do sleep 3; done' \
|
||||
|| (echo "=== keycloak logs ===" && docker logs keycloak --tail 80 && exit 1)
|
||||
echo "keycloak ready."
|
||||
|
||||
# --- Collabora + OnlyOffice (app-provider suite only) ---
|
||||
- name: Start Collabora
|
||||
if: matrix.collaboration == true
|
||||
run: |
|
||||
docker run -d \
|
||||
--name collabora \
|
||||
--network host \
|
||||
--entrypoint bash \
|
||||
-e DONT_GEN_SSL_CERT=set \
|
||||
-e "extra_params=--o:ssl.enable=true --o:ssl.termination=true --o:welcome.enable=false --o:net.frame_ancestors=https://127.0.0.1:9200" \
|
||||
collabora/code:25.04.7.3.1 \
|
||||
-c "coolconfig generate-proof-key && bash /start-collabora-online.sh"
|
||||
timeout 150 bash -c 'until curl -kfsSL https://localhost:9980/hosting/discovery > /dev/null; do sleep 5; done'
|
||||
echo "collabora ready."
|
||||
|
||||
- name: Start OnlyOffice
|
||||
if: matrix.collaboration == true
|
||||
run: |
|
||||
sudo systemctl stop postgresql || true
|
||||
docker run -d \
|
||||
--name onlyoffice \
|
||||
--network host \
|
||||
-e WOPI_ENABLED=true \
|
||||
-e USE_UNAUTHORIZED_STORAGE=true \
|
||||
-v "${{ github.workspace }}/tests/config/ci/only-office.json:/tmp/local.json:ro" \
|
||||
--entrypoint /bin/sh \
|
||||
onlyoffice/documentserver:9.2.1 \
|
||||
-c "set -e
|
||||
cp /tmp/local.json /etc/onlyoffice/documentserver/local.json
|
||||
openssl req -x509 -newkey rsa:4096 -keyout onlyoffice.key -out onlyoffice.crt -sha256 -days 365 -batch -nodes
|
||||
mkdir -p /var/www/onlyoffice/Data/certs
|
||||
cp onlyoffice.key /var/www/onlyoffice/Data/certs/
|
||||
cp onlyoffice.crt /var/www/onlyoffice/Data/certs/
|
||||
chmod 400 /var/www/onlyoffice/Data/certs/onlyoffice.key
|
||||
/app/ds/run-document-server.sh"
|
||||
timeout 150 bash -c 'until curl -kfsSL https://localhost:443/hosting/discovery > /dev/null; do sleep 5; done'
|
||||
echo "onlyoffice ready."
|
||||
|
||||
- name: Run e2e-${{ matrix.suite }}
|
||||
run: E2E_ARGS="${{ matrix.args }}" python3 tests/acceptance/run-e2e.py
|
||||
env:
|
||||
TIKA_NEEDED: ${{ matrix.tika == true && 'true' || 'false' }}
|
||||
KEYCLOAK_NEEDED: ${{ matrix.keycloak == true && 'true' || 'false' }}
|
||||
MFA_NEEDED: ${{ matrix.mfa == true && 'true' || 'false' }}
|
||||
OIDC_NEEDED: ${{ matrix.oidc == true && 'true' || 'false' }}
|
||||
OIDC_IFRAME_NEEDED: ${{ matrix.oidc_iframe == true && 'true' || 'false' }}
|
||||
COLLABORATION_NEEDED: ${{ matrix.collaboration == true && 'true' || 'false' }}
|
||||
FEDERATED_NEEDED: ${{ matrix.federated == true && 'true' || 'false' }}
|
||||
|
||||
- name: Upload tracing result
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
with:
|
||||
name: playwright-traces-${{ matrix.suite }}-${{ github.run_attempt }}
|
||||
path: web/reports/e2e
|
||||
retention-days: 7
|
||||
|
||||
- name: Upload a11y result
|
||||
if: ${{ !cancelled() }}
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
with:
|
||||
name: playwright-a11y-result-${{ matrix.suite }}-${{ github.run_attempt }}
|
||||
path: web/reports/e2e/a11y-report.json
|
||||
retention-days: 7
|
||||
|
||||
litmus:
|
||||
name: litmus
|
||||
needs: [build-and-test]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
|
||||
- name: Install libvips runtime
|
||||
run: |
|
||||
sudo apt-get update -qq
|
||||
# NEEDRESTART_MODE=a: auto-restart services silently; without this, needrestart can fail with exit code 6
|
||||
sudo NEEDRESTART_MODE=a apt-get install -y libvips42t64
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
- name: Restore binary permissions
|
||||
run: chmod +x ocis/bin/ocis
|
||||
|
||||
- name: Run litmus
|
||||
run: python3 tests/acceptance/run-litmus.py
|
||||
|
||||
cs3api:
|
||||
name: cs3api
|
||||
needs: [build-and-test]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
|
||||
- name: Install libvips runtime
|
||||
run: |
|
||||
sudo apt-get update -qq
|
||||
# NEEDRESTART_MODE=a: auto-restart services silently; without this, needrestart can fail with exit code 6
|
||||
sudo NEEDRESTART_MODE=a apt-get install -y libvips42t64
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
- name: Restore binary permissions
|
||||
run: chmod +x ocis/bin/ocis
|
||||
|
||||
- name: Run cs3api validator
|
||||
run: python3 tests/acceptance/run-cs3api.py
|
||||
|
||||
wopi-builtin:
|
||||
name: wopi-builtin
|
||||
needs: [build-and-test]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
|
||||
- name: Install libvips runtime
|
||||
run: |
|
||||
sudo apt-get update -qq
|
||||
# NEEDRESTART_MODE=a: auto-restart services silently; without this, needrestart can fail with exit code 6
|
||||
sudo NEEDRESTART_MODE=a apt-get install -y libvips42t64
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
- name: Restore binary permissions
|
||||
run: chmod +x ocis/bin/ocis
|
||||
|
||||
- name: Run WOPI validator (builtin)
|
||||
run: python3 tests/acceptance/run-wopi.py --type builtin
|
||||
|
||||
wopi-cs3:
|
||||
name: wopi-cs3
|
||||
needs: [build-and-test]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
|
||||
- name: Install libvips runtime
|
||||
run: |
|
||||
sudo apt-get update -qq
|
||||
# NEEDRESTART_MODE=a: auto-restart services silently; without this, needrestart can fail with exit code 6
|
||||
sudo NEEDRESTART_MODE=a apt-get install -y libvips42t64
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
- name: Restore binary permissions
|
||||
run: chmod +x ocis/bin/ocis
|
||||
|
||||
- name: Run WOPI validator (cs3)
|
||||
run: python3 tests/acceptance/run-wopi.py --type cs3
|
||||
|
||||
external-ldap-tests:
|
||||
name: external-ldap-smoke
|
||||
needs: [build-and-test]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
- uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0
|
||||
with:
|
||||
node-version: "24"
|
||||
|
||||
- name: Enable pnpm
|
||||
run: corepack enable && corepack prepare pnpm@10.28.1 --activate
|
||||
|
||||
# web/idp assets must be embedded for `ocis server` to come up (same as run-github.py)
|
||||
- name: Generate assets
|
||||
run: make ci-node-generate
|
||||
|
||||
- name: Build oCIS
|
||||
run: make -C ocis build
|
||||
|
||||
# Boots an external osixia LDAP + oCIS (embedded idm excluded) and runs the
|
||||
# smoke scope against the graph API — exercises the external-directory
|
||||
# read-after-write / retry path (OCISDEV-1030/1032/1033) that the embedded-idm
|
||||
# acceptance jobs never hit.
|
||||
- name: Run external-LDAP smoke
|
||||
run: tests/ldap-smoke/run.sh
|
||||
|
||||
external-ldap-distributed-tests:
|
||||
name: external-ldap-distributed-smoke
|
||||
needs: [build-and-test]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
- uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0
|
||||
with:
|
||||
node-version: "24"
|
||||
|
||||
- name: Enable pnpm
|
||||
run: corepack enable && corepack prepare pnpm@10.28.1 --activate
|
||||
|
||||
# web/idp assets must be embedded for `ocis server` to come up (same as run-github.py)
|
||||
- name: Generate assets
|
||||
run: make ci-node-generate
|
||||
|
||||
- name: Build oCIS
|
||||
run: make -C ocis build
|
||||
|
||||
# Distributed LDAP topology (proxy over an async syncrepl replica + write master);
|
||||
# the replication lag exercises the retry / read-after-write path (OCISDEV-1030/1032/1033).
|
||||
- name: Run external-LDAP distributed smoke
|
||||
run: tests/ldap-smoke-distributed/run.sh
|
||||
|
||||
all-acceptance-tests:
|
||||
needs: [detect-changes, local-api-tests, cli-tests, ldap-pool-tests, core-api-tests, litmus, cs3api, wopi-builtin, wopi-cs3, e2e-tests, external-ldap-tests, external-ldap-distributed-tests]
|
||||
runs-on: ubuntu-latest
|
||||
if: always()
|
||||
steps:
|
||||
- name: Check all jobs passed
|
||||
run: |
|
||||
# If docs-only, all test jobs are expected to be skipped — that's a pass
|
||||
if [[ "${{ needs.detect-changes.outputs.docs-only }}" == "true" ]]; then
|
||||
echo "Docs-only change — skipping tests is expected."
|
||||
exit 0
|
||||
fi
|
||||
if [[ "${{ contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') }}" == "true" ]]; then
|
||||
exit 1
|
||||
fi
|
||||
@@ -1,18 +0,0 @@
|
||||
name: Check licenses
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [master, stable-*]
|
||||
|
||||
jobs:
|
||||
license-check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
|
||||
- name: Install REUSE tool
|
||||
run: pip install reuse
|
||||
|
||||
- name: Run REUSE lint
|
||||
run: reuse lint
|
||||
@@ -1,12 +0,0 @@
|
||||
name: Validate commit message
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [master, stable-*]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
uses: owncloud/reusable-workflows/.github/workflows/semantic-git-message.yml@main
|
||||
@@ -1,79 +0,0 @@
|
||||
name: test deployment example
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "0 0 * * *" # every day at 00:00 UTC
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- example: ocis_full
|
||||
urls: "https://ocis.owncloud.test"
|
||||
- example: ocis_ldap
|
||||
urls: "https://ocis.owncloud.test https://ldap.owncloud.test"
|
||||
- example: ocis_multi
|
||||
urls: "https://ocis.owncloud.test https://ocis.ocm.owncloud.test"
|
||||
- example: ocis_ocm
|
||||
urls: "https://ocis.owncloud.test https://ocis.ocm.owncloud.test https://ocis.ocm.next.owncloud.test"
|
||||
- example: ocis_keycloak
|
||||
urls: "https://ocis.owncloud.test https://keycloak.owncloud.test"
|
||||
|
||||
steps:
|
||||
- name: Checkout ocis repo
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
repository: owncloud/ocis
|
||||
|
||||
- name: Set up Docker Compose
|
||||
uses: docker/setup-compose-action@16feee727cbdc83b6a014e6cc26fec4a79bcf30c # v2.2.0
|
||||
|
||||
- name: Prepare hosts entry
|
||||
run: |
|
||||
echo "127.0.0.1 ocis.owncloud.test collabora.owncloud.test keycloak.owncloud.test mail.owncloud.test minio.owncloud.test onlyoffice.owncloud.test tika ldap.owncloud.test ocis.ocm.owncloud.test ocis.ocm.next.owncloud.test onlyoffice.owncloud.test" | sudo tee -a /etc/hosts
|
||||
|
||||
- name: Run compose stack
|
||||
working-directory: deployments/examples/${{ matrix.example }}
|
||||
run: |
|
||||
set -e
|
||||
echo "=== Running ${{ matrix.example }} ==="
|
||||
docker compose up -d
|
||||
|
||||
- name: Wait for services
|
||||
run: |
|
||||
set -e
|
||||
|
||||
URLS="${{ matrix.urls }}"
|
||||
|
||||
for url in $URLS; do
|
||||
echo "=== Waiting for $url ==="
|
||||
|
||||
end=$((SECONDS+150))
|
||||
ready=false
|
||||
|
||||
while [ $SECONDS -lt $end ]; do
|
||||
echo "Trying $url"
|
||||
if curl -kfsS --max-time 5 "$url" > /dev/null; then
|
||||
echo "✅ $url is ready"
|
||||
ready=true
|
||||
break
|
||||
fi
|
||||
echo "⏳ Not ready yet, retrying in 5s..."
|
||||
sleep 5
|
||||
done
|
||||
|
||||
if [ "$ready" = false ]; then
|
||||
echo "❌ $url never became ready"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
- name: Tear down
|
||||
if: always()
|
||||
working-directory: deployments/examples/${{ matrix.example }}
|
||||
run: docker compose down -v
|
||||
@@ -1,54 +0,0 @@
|
||||
name: k6 Load Test
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened]
|
||||
schedule:
|
||||
- cron: '0 1 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: k6-load-test-server
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
k6-load-test:
|
||||
name: k6-load-test
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: owncloudci/alpine:latest
|
||||
if: >-
|
||||
github.event_name == 'schedule' ||
|
||||
github.event_name == 'workflow_dispatch' ||
|
||||
(github.event_name == 'pull_request' &&
|
||||
contains(github.event.pull_request.title || '', 'k6-test'))
|
||||
env:
|
||||
SSH_OCIS_REMOTE: ${{ secrets.SSH_OCIS_REMOTE }}
|
||||
SSH_OCIS_USERNAME: ${{ secrets.SSH_OCIS_USERNAME }}
|
||||
SSH_OCIS_PASSWORD: ${{ secrets.SSH_OCIS_PASSWORD }}
|
||||
TEST_SERVER_URL: ${{ secrets.TEST_SERVER_URL }}
|
||||
SSH_K6_REMOTE: ${{ secrets.SSH_K6_REMOTE }}
|
||||
SSH_K6_USERNAME: ${{ secrets.SSH_K6_USERNAME }}
|
||||
SSH_K6_PASSWORD: ${{ secrets.SSH_K6_PASSWORD }}
|
||||
OCIS_COMMIT_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
|
||||
- name: Install SSH dependencies
|
||||
run: apk add --no-cache openssh-client sshpass
|
||||
|
||||
- name: Run k6 load tests
|
||||
if: ${{ !cancelled() }}
|
||||
run: sh tests/config/drone/run_k6_tests.sh
|
||||
|
||||
- name: Retrieve OCIS logs
|
||||
if: ${{ !cancelled() }}
|
||||
run: sh tests/config/drone/run_k6_tests.sh --ocis-log
|
||||
|
||||
- name: Show Grafana dashboard link
|
||||
if: ${{ !cancelled() }}
|
||||
run: |
|
||||
echo "Grafana Dashboard: https://grafana.k6.infra.owncloud.works"
|
||||
@@ -1,84 +0,0 @@
|
||||
name: Release NPM packages
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "babel-preset-v*"
|
||||
- "design-system-v*"
|
||||
- "eslint-config-v*"
|
||||
- "extension-sdk-v*"
|
||||
- "prettier-config-v*"
|
||||
- "tsconfig-v*"
|
||||
- "web-client-v*"
|
||||
- "web-pkg-v*"
|
||||
- "web-test-helpers-v*"
|
||||
|
||||
jobs:
|
||||
release-npm:
|
||||
name: Publish NPM package
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
defaults:
|
||||
run:
|
||||
working-directory: web
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
node-version: 24.15.0
|
||||
registry-url: "https://registry.npmjs.org"
|
||||
|
||||
- name: Setup pnpm
|
||||
run: corepack enable && corepack prepare pnpm@10.33.3 --activate
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Determine package
|
||||
id: package
|
||||
run: |
|
||||
TAG="${{ github.ref_name }}"
|
||||
PACKAGES="babel-preset design-system eslint-config extension-sdk prettier-config tsconfig web-client web-pkg web-test-helpers"
|
||||
for pkg in $PACKAGES; do
|
||||
if [[ "$TAG" == "${pkg}-v"* ]]; then
|
||||
echo "name=$pkg" >> "$GITHUB_OUTPUT"
|
||||
echo "version=${TAG#${pkg}-v}" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
echo "tag '$TAG' does not match any known package prefix: $PACKAGES"
|
||||
exit 1
|
||||
|
||||
- name: Verify package version
|
||||
run: |
|
||||
PKG="${{ steps.package.outputs.name }}"
|
||||
VERSION="${{ steps.package.outputs.version }}"
|
||||
ACTUAL_VERSION=$(jq -r '.version' < "packages/${PKG}/package.json")
|
||||
echo "Build ${PKG} ${VERSION} package.json: ${ACTUAL_VERSION}"
|
||||
if [ "${ACTUAL_VERSION}" != "${VERSION}" ]; then
|
||||
echo "git tag does not match version in web/packages/${PKG}/package.json"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Build tokens
|
||||
run: pnpm build:tokens
|
||||
|
||||
- name: Build package
|
||||
run: |
|
||||
PKG="${{ steps.package.outputs.name }}"
|
||||
case "$PKG" in
|
||||
design-system|web-client|web-pkg|web-test-helpers)
|
||||
pnpm --filter "@ownclouders/${PKG}" vite build
|
||||
;;
|
||||
esac
|
||||
|
||||
- name: Publish to NPM
|
||||
run: |
|
||||
pnpm publish \
|
||||
--no-git-checks --filter "@ownclouders/${{ steps.package.outputs.name }}" \
|
||||
--access public --tag latest
|
||||
@@ -1,416 +0,0 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
branches:
|
||||
- 'feat/release-pipeline**'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version_override:
|
||||
description: 'Version override (leave empty to auto-detect from latest tag)'
|
||||
type: string
|
||||
default: ''
|
||||
|
||||
env:
|
||||
PRODUCTION_RELEASE_TAGS: '5.0,7,8'
|
||||
DOCKER_REPO_ROLLING: owncloud/ocis-rolling
|
||||
DOCKER_REPO_PRODUCTION: owncloud/ocis
|
||||
NODE_VERSION: '24'
|
||||
PNPM_VERSION: '10.28.1'
|
||||
GOLANG_BUILD_IMAGE: 'golang:1.26.8-alpine3.23@sha256:a8fa79c5bd40d880b52bd3b6d7669ecdcfd00e85facdd427d279efb5ddd79cb1'
|
||||
|
||||
jobs:
|
||||
determine-release-type:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
version: ${{ steps.info.outputs.version }}
|
||||
is_production: ${{ steps.info.outputs.is_production }}
|
||||
is_prerelease: ${{ steps.info.outputs.is_prerelease }}
|
||||
docker_repos: ${{ steps.info.outputs.docker_repos }}
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
if: ${{ github.ref_type == 'branch' || (github.event_name == 'workflow_dispatch' && inputs.version_override == '') }}
|
||||
with:
|
||||
fetch-depth: 0
|
||||
fetch-tags: true
|
||||
|
||||
- id: info
|
||||
run: |
|
||||
next_dev() {
|
||||
# If latest tag is already a pre-release (e.g. v8.0.2-dev.1), reuse its base
|
||||
# version (8.0.2-dev.1) so repeated branch runs don't bump the patch counter.
|
||||
# If latest tag is a production release (e.g. v8.0.1), increment patch (8.0.2-dev.1).
|
||||
local tag=$(git tag --sort=-version:refname | grep -m1 '^v' || echo "v0.0.0")
|
||||
local ver="${tag#v}"
|
||||
if [[ "$ver" == *"-"* ]]; then
|
||||
echo "${ver%%-*}-dev.1"
|
||||
else
|
||||
IFS='.' read -r M m p <<< "$ver"
|
||||
echo "${M}.${m}.$((p + 1))-dev.1"
|
||||
fi
|
||||
}
|
||||
|
||||
if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
|
||||
VERSION="${{ inputs.version_override }}"
|
||||
[[ -z "$VERSION" ]] && VERSION=$(next_dev)
|
||||
elif [[ "${{ github.ref_type }}" == "branch" ]]; then
|
||||
VERSION=$(next_dev)
|
||||
else
|
||||
VERSION="${GITHUB_REF#refs/tags/v}"
|
||||
fi
|
||||
|
||||
IS_PRODUCTION=false
|
||||
for TAG in ${PRODUCTION_RELEASE_TAGS//,/ }; do
|
||||
[[ "$VERSION" == "$TAG"* ]] && IS_PRODUCTION=true && break
|
||||
done
|
||||
|
||||
[[ "$VERSION" == *"-"* ]] && IS_PRERELEASE=true || IS_PRERELEASE=false
|
||||
|
||||
if [[ "$IS_PRODUCTION" == "true" && "$IS_PRERELEASE" == "false" ]]; then
|
||||
REPOS=[\"$DOCKER_REPO_ROLLING\",\"$DOCKER_REPO_PRODUCTION\"]
|
||||
else
|
||||
REPOS=[\"$DOCKER_REPO_ROLLING\"]
|
||||
fi
|
||||
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
echo "is_production=$IS_PRODUCTION" >> $GITHUB_OUTPUT
|
||||
echo "is_prerelease=$IS_PRERELEASE" >> $GITHUB_OUTPUT
|
||||
echo "docker_repos=$REPOS" >> $GITHUB_OUTPUT
|
||||
|
||||
generate-code:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [determine-release-type]
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
- run: npm install --silent -g yarn npx --force
|
||||
- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v4
|
||||
with:
|
||||
version: ${{ env.PNPM_VERSION }}
|
||||
- run: pnpm config set store-dir ./.pnpm-store && make ci-node-generate
|
||||
env:
|
||||
CHROMEDRIVER_SKIP_DOWNLOAD: 'true'
|
||||
- run: make ci-go-generate
|
||||
env:
|
||||
BUF_TOKEN: ${{ secrets.BUF_API_TOKEN }}
|
||||
- name: bump LatestTag
|
||||
run: |
|
||||
VERSION="${{ needs.determine-release-type.outputs.version }}"
|
||||
sed -i "s/LatestTag = \".*\"/LatestTag = \"$VERSION\"/" ocis-pkg/version/version.go
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: generated-code
|
||||
path: |
|
||||
.
|
||||
!.git
|
||||
!web
|
||||
retention-days: 1
|
||||
|
||||
docker-build:
|
||||
if: false
|
||||
name: docker-build (${{ matrix.arch }}, ${{ matrix.repo }})
|
||||
runs-on: ${{ matrix.arch == 'amd64' && 'ubuntu-24.04' || 'ubuntu-24.04-arm' }}
|
||||
needs: [determine-release-type, generate-code, security-scan-trivy]
|
||||
strategy:
|
||||
matrix:
|
||||
arch: [amd64, arm64]
|
||||
repo: ${{ fromJSON(needs.determine-release-type.outputs.docker_repos) }}
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: generated-code
|
||||
path: .
|
||||
- uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4.0.0
|
||||
- uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0
|
||||
with:
|
||||
username: ${{ vars.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
- id: goversion
|
||||
uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
- run: |
|
||||
ALPINE_VERSION=$(grep '^FROM.*alpine:' ocis/docker/Dockerfile.linux.${{ matrix.arch }} | grep -o 'alpine:[0-9.]*' | cut -d: -f2 | cut -d. -f1,2)
|
||||
docker run --rm \
|
||||
-v "${{ github.workspace }}:/workspace" \
|
||||
-w /workspace \
|
||||
"golang:${{ steps.goversion.outputs.go-version }}-alpine${ALPINE_VERSION}" \
|
||||
sh -c "apk add --no-cache bash gcc musl-dev vips-dev make git && \
|
||||
git config --global --add safe.directory /workspace && \
|
||||
CGO_ENABLED=1 ENABLE_VIPS=true VERSION=${{ needs.determine-release-type.outputs.version }} \
|
||||
make -C ocis release-linux-docker-${{ matrix.arch }}"
|
||||
- id: tags
|
||||
run: |
|
||||
VERSION="${{ needs.determine-release-type.outputs.version }}"
|
||||
REPO="${{ matrix.repo }}"
|
||||
ARCH="${{ matrix.arch }}"
|
||||
printf "tags<<EOF\n%s\nEOF\n" \
|
||||
"${REPO}:${VERSION}-linux-${ARCH}" >> $GITHUB_OUTPUT
|
||||
- id: build
|
||||
uses: docker/build-push-action@d08e5c354a6adb9ed34480a06d141179aa583294 # v7.0.0
|
||||
with:
|
||||
context: ocis
|
||||
file: ocis/docker/Dockerfile.linux.${{ matrix.arch }}
|
||||
platforms: linux/${{ matrix.arch }}
|
||||
load: true
|
||||
push: false
|
||||
provenance: false
|
||||
build-args: |
|
||||
REVISION=${{ github.sha }}
|
||||
VERSION=${{ needs.determine-release-type.outputs.version }}
|
||||
tags: ${{ steps.tags.outputs.tags }}
|
||||
- id: trivy
|
||||
uses: aquasecurity/trivy-action@57a97c7e7821a5776cebc9bb87c984fa69cba8f1 # v0.35.0
|
||||
continue-on-error: true
|
||||
with:
|
||||
image-ref: ${{ steps.tags.outputs.tags }}
|
||||
format: table
|
||||
exit-code: 1
|
||||
severity: HIGH,CRITICAL
|
||||
ignore-unfixed: true
|
||||
skip-files: /usr/bin/gomplate,/usr/bin/wait-for
|
||||
hide-progress: true
|
||||
env:
|
||||
TRIVY_IGNOREFILE: .trivyignore
|
||||
- name: Block on vulnerabilities
|
||||
if: steps.trivy.outcome == 'failure'
|
||||
run: |
|
||||
echo "::error title=Security scan blocked release::Image ${{ steps.tags.outputs.tags }} has HIGH or CRITICAL vulnerabilities (see Trivy report above). Fix all findings before releasing."
|
||||
exit 1
|
||||
- name: push
|
||||
if: steps.trivy.outcome == 'success'
|
||||
run: docker push ${{ steps.tags.outputs.tags }}
|
||||
|
||||
docker-scan:
|
||||
name: docker-scan (${{ matrix.arch }}, ${{ matrix.repo }})
|
||||
runs-on: ubuntu-latest
|
||||
needs: [determine-release-type, docker-build]
|
||||
strategy:
|
||||
matrix:
|
||||
arch: [amd64]
|
||||
repo: ${{ fromJSON(needs.determine-release-type.outputs.docker_repos) }}
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: aquasecurity/trivy-action@57a97c7e7821a5776cebc9bb87c984fa69cba8f1 # v0.35.0
|
||||
id: trivy
|
||||
continue-on-error: true
|
||||
with:
|
||||
image-ref: ${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}-linux-${{ matrix.arch }}
|
||||
format: table
|
||||
exit-code: 1
|
||||
severity: HIGH,CRITICAL
|
||||
ignore-unfixed: true
|
||||
skip-files: /usr/bin/gomplate,/usr/bin/wait-for
|
||||
hide-progress: true
|
||||
env:
|
||||
TRIVY_IGNOREFILE: .trivyignore
|
||||
|
||||
- name: Block on vulnerabilities
|
||||
if: steps.trivy.outcome == 'failure'
|
||||
run: |
|
||||
echo "::error title=Security scan blocked release::Image ${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}-linux-${{ matrix.arch }} has HIGH or CRITICAL vulnerabilities (see Trivy report above). Fix all findings before releasing."
|
||||
exit 1
|
||||
|
||||
docker-manifest:
|
||||
if: false
|
||||
name: docker-manifest (${{ matrix.repo }})
|
||||
runs-on: ubuntu-latest
|
||||
needs: [determine-release-type, docker-build, docker-scan]
|
||||
strategy:
|
||||
matrix:
|
||||
repo: ${{ fromJSON(needs.determine-release-type.outputs.docker_repos) }}
|
||||
steps:
|
||||
- uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0
|
||||
with:
|
||||
username: ${{ vars.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
- if: ${{ contains(matrix.repo, 'rolling') }}
|
||||
run: |
|
||||
docker buildx imagetools create \
|
||||
-t "${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}" \
|
||||
"${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}-linux-amd64" \
|
||||
"${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}-linux-arm64"
|
||||
- if: ${{ !contains(matrix.repo, 'rolling') }}
|
||||
run: |
|
||||
docker buildx imagetools create \
|
||||
-t "${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}" \
|
||||
"${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}-linux-amd64" \
|
||||
"${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}-linux-arm64"
|
||||
|
||||
docker-readme:
|
||||
if: false
|
||||
name: docker-readme (${{ matrix.repo }})
|
||||
runs-on: ubuntu-latest
|
||||
needs: [determine-release-type, docker-manifest]
|
||||
strategy:
|
||||
matrix:
|
||||
repo: ${{ fromJSON(needs.determine-release-type.outputs.docker_repos) }}
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: peter-evans/dockerhub-description@1b9a80c056b620d92cedb9d9b5a223409c68ddfa # v5.0.0
|
||||
with:
|
||||
username: ${{ vars.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
repository: ${{ matrix.repo }}
|
||||
readme-filepath: ocis/README.md
|
||||
|
||||
build-binaries:
|
||||
name: build-binaries (${{ matrix.os }})
|
||||
runs-on: ubuntu-latest
|
||||
needs: [determine-release-type, generate-code]
|
||||
strategy:
|
||||
matrix:
|
||||
os: [linux, darwin]
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: generated-code
|
||||
path: .
|
||||
- uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
- run: |
|
||||
make -C ocis release-${{ matrix.os }} OUTPUT=${{ needs.determine-release-type.outputs.version }}
|
||||
make -C ocis release-finish
|
||||
if [[ "${{ matrix.os }}" == "linux" ]]; then
|
||||
cp assets/End-User-License-Agreement-for-ownCloud-Infinite-Scale.pdf ocis/dist/release/
|
||||
fi
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: binaries-${{ matrix.os }}
|
||||
path: ocis/dist/release/*
|
||||
retention-days: 1
|
||||
|
||||
security-scan-trivy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: aquasecurity/trivy-action@57a97c7e7821a5776cebc9bb87c984fa69cba8f1 # v0.35.0
|
||||
with:
|
||||
scan-type: fs
|
||||
format: table
|
||||
exit-code: 1
|
||||
severity: CRITICAL,HIGH
|
||||
trivy-config: .trivy.yaml
|
||||
|
||||
license-check:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [determine-release-type, generate-code]
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: generated-code
|
||||
path: .
|
||||
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
- uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
- run: npm install --silent -g yarn npx "pnpm@$PNPM_VERSION" --force
|
||||
# web is excluded from the generated-code artifact (see generate-code) to
|
||||
# avoid OOM on upload, so its node_modules — which provides the
|
||||
# license-checker-rseidelsohn binary — must be reinstalled here.
|
||||
- run: cd web && pnpm install
|
||||
- run: make ci-node-check-licenses && make ci-node-save-licenses
|
||||
- run: make ci-go-check-licenses && make ci-go-save-licenses
|
||||
- run: tar -czf third-party-licenses.tar.gz -C third-party-licenses .
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: third-party-licenses
|
||||
path: third-party-licenses.tar.gz
|
||||
retention-days: 1
|
||||
|
||||
generate-changelog:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [determine-release-type]
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
- run: |
|
||||
make changelog CHANGELOG_VERSION=$(echo "${{ needs.determine-release-type.outputs.version }}" | cut -d'-' -f1)
|
||||
# calens produces empty output when no versioned changelog directory exists (e.g. dev builds).
|
||||
# Fall back to a pointer to the unreleased entries.
|
||||
if [[ $(wc -l < ocis/dist/CHANGELOG.md) -lt 5 ]]; then
|
||||
echo "Development release — no release notes yet. See [unreleased changes](https://github.com/owncloud/ocis/tree/master/changelog/unreleased/)." > ocis/dist/CHANGELOG.md
|
||||
fi
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: changelog
|
||||
path: ocis/dist/CHANGELOG.md
|
||||
retention-days: 1
|
||||
|
||||
create-github-release:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [determine-release-type, build-binaries, license-check, generate-changelog, security-scan-trivy]
|
||||
steps:
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: binaries-linux
|
||||
path: release-assets
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: binaries-darwin
|
||||
path: release-assets
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: third-party-licenses
|
||||
path: release-assets
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: changelog
|
||||
path: .
|
||||
- uses: softprops/action-gh-release@718ea10b132b3b2eba29c1007bb80653f286566b # v3.0.1
|
||||
with:
|
||||
tag_name: v${{ needs.determine-release-type.outputs.version }}
|
||||
name: v${{ needs.determine-release-type.outputs.version }}
|
||||
body_path: CHANGELOG.md
|
||||
prerelease: ${{ needs.determine-release-type.outputs.is_prerelease == 'true' }}
|
||||
files: release-assets/*
|
||||
|
||||
audit-release:
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- determine-release-type
|
||||
- generate-code
|
||||
- build-binaries
|
||||
- security-scan-trivy
|
||||
- license-check
|
||||
- generate-changelog
|
||||
- create-github-release
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: binaries-linux
|
||||
path: release-assets
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: binaries-darwin
|
||||
path: release-assets
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: third-party-licenses
|
||||
path: release-assets
|
||||
- run: |
|
||||
python3 scripts/audit-release.py \
|
||||
--version "${{ needs.determine-release-type.outputs.version }}" \
|
||||
--dir release-assets/ \
|
||||
--github-release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
name: Remove stale branches
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
dry-run:
|
||||
description: 'Run in dry-run mode (no actual branch deletion)'
|
||||
required: true
|
||||
default: 'false'
|
||||
type: boolean
|
||||
schedule:
|
||||
- cron: "0 0 * * *" # Everday at midnight
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
remove-stale-branches:
|
||||
name: Remove Stale Branches
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: fpicalausa/remove-stale-branches@9b829bc2975ade0c61e64e9613def53ec0732440 # v2.6.1
|
||||
with:
|
||||
ignore-unknown-authors: true
|
||||
default-recipient: "kobergj"
|
||||
dry-run: ${{ inputs.dry-run || 'false' }} # fallback to dry-run
|
||||
exempt-branches-regex: "^(main$|master$|stable-|release-|docs$|docs-stable-)"
|
||||
exempt-protected-branches: true
|
||||
operations-per-run: 30
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
name: Translation Sync
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 2 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
sync:
|
||||
uses: owncloud/reusable-workflows/.github/workflows/translation-sync.yml@main
|
||||
with:
|
||||
mode: make
|
||||
reviewers: kobergj,mmattel # individual users
|
||||
# team_reviewers: owncloud/ocis-team # and/or a GitHub team slug if exists
|
||||
sub_path: .
|
||||
secrets:
|
||||
TX_TOKEN: ${{ secrets.TX_TOKEN }}
|
||||
TRANSLATION_APP_ID: ${{ secrets.TRANSLATION_APP_ID }}
|
||||
TRANSLATION_APP_PRIVATE_KEY: ${{ secrets.TRANSLATION_APP_PRIVATE_KEY }}
|
||||
|
||||
# web/ is a pnpm workspace nested inside the repo, not covered by the
|
||||
# root-level L10N_MODULES/sub_path: . sync above (that job has no
|
||||
# package.json at the repo root, so a pnpm install there would be a
|
||||
# no-op/fail). Run it as its own invocation scoped to sub_path: web,
|
||||
# sequenced after `sync` since the reusable workflow always pushes to
|
||||
# the same hardcoded chore/translations-update branch.
|
||||
sync-web:
|
||||
needs: sync
|
||||
uses: owncloud/reusable-workflows/.github/workflows/translation-sync.yml@main
|
||||
with:
|
||||
mode: make
|
||||
package_manager: pnpm
|
||||
reviewers: kobergj,mmattel
|
||||
sub_path: web
|
||||
secrets:
|
||||
TX_TOKEN: ${{ secrets.TX_TOKEN }}
|
||||
TRANSLATION_APP_ID: ${{ secrets.TRANSLATION_APP_ID }}
|
||||
TRANSLATION_APP_PRIVATE_KEY: ${{ secrets.TRANSLATION_APP_PRIVATE_KEY }}
|
||||
@@ -1,105 +0,0 @@
|
||||
name: Web Tests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [master, stable-*]
|
||||
|
||||
jobs:
|
||||
detect-web-changes:
|
||||
name: detect-web-changes
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
web-changed: ${{ steps.check.outputs.web-changed }}
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Check if web/ changed
|
||||
id: check
|
||||
run: |
|
||||
if [[ "${{ github.event_name }}" == "push" ]]; then
|
||||
echo "web-changed=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
PR_TITLE="${{ github.event.pull_request.title }}"
|
||||
if echo "$PR_TITLE" | grep -qi "\[full-ci\]"; then
|
||||
echo "web-changed=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
CHANGED_FILES=$(git diff --name-only "${{ github.event.pull_request.base.sha }}" "${{ github.sha }}" 2>/dev/null || git diff --name-only HEAD~1)
|
||||
|
||||
WEB_CHANGED=false
|
||||
while IFS= read -r file; do
|
||||
case "$file" in
|
||||
web/*) WEB_CHANGED=true; break ;;
|
||||
.github/workflows/web-tests.yml) WEB_CHANGED=true; break ;;
|
||||
esac
|
||||
done <<< "$CHANGED_FILES"
|
||||
|
||||
echo "web-changed=$WEB_CHANGED" >> "$GITHUB_OUTPUT"
|
||||
echo "web/ changed: $WEB_CHANGED"
|
||||
|
||||
web-build-test:
|
||||
name: web-build-test
|
||||
needs: [detect-web-changes]
|
||||
if: needs.detect-web-changes.outputs.web-changed == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: web
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
|
||||
with:
|
||||
version: 10.33.3
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
node-version: 24.15.0
|
||||
cache: pnpm
|
||||
cache-dependency-path: web/pnpm-lock.yaml
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Check licenses
|
||||
run: pnpm licenses:check
|
||||
|
||||
- name: Save licenses
|
||||
run: pnpm licenses:csv && pnpm licenses:save
|
||||
|
||||
- name: Check types
|
||||
run: pnpm check:types
|
||||
|
||||
- name: Check format
|
||||
run: pnpm check:format
|
||||
|
||||
- name: Lint
|
||||
run: pnpm lint
|
||||
|
||||
- name: Run unit tests
|
||||
run: pnpm test:unit --coverage
|
||||
|
||||
- name: Build
|
||||
run: pnpm build
|
||||
|
||||
web-tests-passed:
|
||||
name: web-tests-passed
|
||||
needs: [detect-web-changes, web-build-test]
|
||||
runs-on: ubuntu-latest
|
||||
if: always()
|
||||
steps:
|
||||
- name: Check web-build-test passed or was skipped
|
||||
run: |
|
||||
if [[ "${{ needs.web-build-test.result }}" == "failure" || "${{ needs.web-build-test.result }}" == "cancelled" ]]; then
|
||||
exit 1
|
||||
fi
|
||||
@@ -1,31 +0,0 @@
|
||||
name: Weekly Pipeline Report
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
pull_request:
|
||||
branches:
|
||||
- feat/ci-report-tool
|
||||
schedule:
|
||||
- cron: "0 8 * * 1" # Every Monday at 8:00 AM UTC
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
generate-report:
|
||||
name: Generate Pipeline Report
|
||||
runs-on: ubuntu-latest
|
||||
container: golang:1.25-alpine
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
|
||||
|
||||
- name: Run CI Reporter
|
||||
working-directory: tools/ci-reporter
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
GOWORK=off go run ./cmd/list-flaky-tests \
|
||||
--github-token "$GITHUB_TOKEN" \
|
||||
--workflow acceptance-tests.yml \
|
||||
--since 4w
|
||||
@@ -0,0 +1,272 @@
|
||||
---
|
||||
title: Discord ログイン
|
||||
weight: 30
|
||||
geekdocRepo: https://github.com/owncloud/ocis
|
||||
geekdocEditPath: edit/master/docs/services/idp
|
||||
geekdocFilePath: discord-login.md
|
||||
---
|
||||
|
||||
{{< toc >}}
|
||||
|
||||
## 概要
|
||||
|
||||
idp のログイン画面に「Discord でログイン」ボタンを追加する機能です(Reverse Cloud 独自機能)。管理者が指定した Discord サーバー(guild)のメンバーだけがログインできます。
|
||||
|
||||
- Client ID / Client Secret / 許可するサーバー ID は、管理設定画面(Admin Settings > General)で設定します。
|
||||
- 初めてログインした Discord ユーザーには、作成するアカウントのユーザー名を入力してもらいます。
|
||||
- Discord と紐付いたアカウントは、ID トークンの `email_verified` が `true` になります。
|
||||
- 新規登録の受付(Web / Discord)と管理者承認は、管理設定画面の「登録」セクションで切り替えます([新規登録の設定と承認](#新規登録の設定と承認))。
|
||||
|
||||
## 前提条件
|
||||
|
||||
次の条件がすべてそろったときだけ有効になります。どれかが欠けると、idp の起動時に `discord login is disabled` を警告ログに出し、機能を無効にします。
|
||||
|
||||
| 条件 | 設定 |
|
||||
|---|---|
|
||||
| identity manager が ldap | `IDP_IDENTITY_MANAGER=ldap`(デフォルト) |
|
||||
| JWT シークレット | `OCIS_JWT_SECRET` または `IDP_JWT_SECRET` |
|
||||
| サービスアカウント | `OCIS_SERVICE_ACCOUNT_ID` / `OCIS_SERVICE_ACCOUNT_SECRET`(または `IDP_` 接頭辞) |
|
||||
| 公開 URL | `OCIS_URL` |
|
||||
| reva gateway | idp の reva 設定(通常はデフォルトのまま) |
|
||||
|
||||
`ocis init` は、生成する `ocis.yaml` の `idp.service_account` にサービスアカウントを書き込むようにしました。
|
||||
|
||||
ログイン画面にボタンが出るのは、管理画面で「有効」にし、Client ID・Client Secret・サーバー ID をすべて保存したときだけです。
|
||||
|
||||
## Discord 側の準備
|
||||
|
||||
1. Discord Developer Portal でアプリケーションを作成します。
|
||||
2. OAuth2 の Redirects に、管理設定画面に表示される Redirect URI(`<OCIS_URL>/oauth2/discord/callback`)を登録します。
|
||||
3. Client ID と Client Secret を管理設定画面に入力します。
|
||||
4. 許可するサーバーの ID(開発者モードでサーバーを右クリックしてコピー)を入力し、有効にして保存します。
|
||||
|
||||
要求するスコープは `identify email guilds` です。
|
||||
|
||||
## ログインの流れ
|
||||
|
||||
1. ユーザーがログイン画面の「Discord でログイン」を押すと、`GET /oauth2/discord/login` に元の OIDC authorize クエリを付けて遷移します。
|
||||
2. idp は state を生成し、署名付きの state Cookie に保存して Discord の認可画面へリダイレクトします。認可済みのアプリなら同意画面を省略します(`prompt=none`)。
|
||||
3. Discord から `GET /oauth2/discord/callback` に戻ります。idp は次の順に処理します。
|
||||
1. state Cookie の署名・有効期限と、クエリの `state` の一致を確認します。
|
||||
2. 認可コードをアクセストークンに交換します。
|
||||
3. `GET /users/@me` でユーザー情報、`GET /users/@me/guilds` で参加サーバーを取得します(200 件ずつ、最大 10 ページ)。
|
||||
4. 許可サーバーのメンバーでなければ 403 のエラー画面を出します。
|
||||
5. 対応する oCIS アカウントを探します(後述)。見つからなければユーザー名入力画面を出します。
|
||||
4. アカウントが決まったら、lico の通常のログオン Cookie(`__Secure-KKT`)を発行します。ID/パスワードでログインしたときと同じ Cookie です。
|
||||
5. 同一オリジンの中継ページから、元の OIDC authorize リクエストに戻ります。ログオン Cookie は SameSite=Strict なので、discord.com から始まったリダイレクトの連鎖では送られません。そのため中継ページを挟んでいます。
|
||||
- 戻り先のクエリからは `flow` と、`prompt` の `login` / `select_account` を取り除き、`identifier=must` を付けます。
|
||||
- authorize クエリがない場合は `/`(Web UI)に戻ります。
|
||||
|
||||
## アカウントの決め方
|
||||
|
||||
`services/idp/pkg/discord/provision.go` の `GraphProvisioner.Lookup` が、次の順に探します。
|
||||
|
||||
1. **紐付け済みアカウント**: LDAP の `oCExternalIdentity` 属性が `$ https://discord.com $ <Discord ID>` のユーザーです。Graph API の `$filter` は identities での検索に対応していないため、idp の LDAP 接続設定で LDAP を直接検索します(`ldapidentity.go`)。無効化されたユーザーも検索対象に含めるので、無効化されたアカウントの持ち主に 2 つ目のアカウントは作られません。2 件以上見つかった場合はエラーにします。
|
||||
2. **確認済みメールが一致する既存アカウント**: Discord がメールを確認済み(`verified: true`)と返したときだけ、Graph でメールが完全一致(大文字小文字は無視)するユーザーを探します。1 件だけ見つかれば Discord の identity を追加して紐付けます。既存アカウントの表示名やメールは変えません。2 件以上あるとき、または別の Discord ID に紐付いているときはエラーにします。未確認のメールで紐付けると乗っ取りに使えるため、未確認メールは使いません。
|
||||
3. **どちらもない**: ユーザー名入力画面を出します。
|
||||
|
||||
## ユーザー名入力画面
|
||||
|
||||
- 入力欄の初期値は Discord のユーザー名(小文字化して、使える形式のときだけ)です。
|
||||
- 使えるユーザー名は 3〜32 文字で、先頭は英字か `_`、残りは英数字と `.` `_` `-` です。
|
||||
- フォームは `POST /oauth2/discord/signup` に送信されます。
|
||||
- callback で確認した Discord のプロフィール(ID、ユーザー名、表示名、確認済みメール)は、署名付きの signup Cookie に入れて持ち回ります。そのため、送信時にサーバー参加チェックはやり直しません。
|
||||
- 送信時はまず `Lookup` をもう一度実行します。別タブなどで既にアカウントができていれば、それを使います。
|
||||
- ルール違反なら 400、使用済みなら 409 を返し、入力内容を残したまま画面を出し直します。
|
||||
|
||||
作成するアカウントの内容は次のとおりです。作成は Graph API にサービスアカウントで行います。
|
||||
|
||||
| 属性 | 値 |
|
||||
|---|---|
|
||||
| ユーザー名 | 入力された値 |
|
||||
| 表示名 | Discord の `global_name`(なければ `username`) |
|
||||
| メール | Discord で確認済みのときだけ設定 |
|
||||
| 有効 | true |
|
||||
| identities | issuer `https://discord.com`、issuerAssignedId は Discord ID |
|
||||
|
||||
作成後はプロフィールを同期しません。Discord 側で表示名やメールを変えても、oCIS のアカウントは作成時の値のままです。
|
||||
|
||||
## email_verified
|
||||
|
||||
lico の LDAP バックエンドは、全ユーザーで `EmailVerified()` に固定で `false` を返します。oCIS の LDAP と Graph には「メール確認済み」を保存する属性がないため、ID トークンのクレームで表すしかありません。
|
||||
|
||||
`services/idp/pkg/backends/ldapverified/` に次のものを用意しました。
|
||||
|
||||
- `Backend`: lico の LDAP identifier backend を包み、`GetUser` で返すユーザーの `EmailVerified()` を上書きします。ユーザーに `https://discord.com` の identity があり、メールが空でなければ `true` を返します。それ以外は元の値(`false`)のままです。
|
||||
- `Register`: 上の Backend を使う `ldap` identity manager を lico の bootstrap に登録します。中身は lico v0.68.0 の `bootstrap/backends/ldap` と同じで、backend を包む部分だけが違います。
|
||||
|
||||
補足:
|
||||
|
||||
- バックエンド名は `identifier-ldap` のままです。既存のログオン Cookie はそのまま使えます。
|
||||
- 紐付けの確認で LDAP 検索に失敗したときは、警告ログを出して `false` のまま扱います。
|
||||
- ラッパーの登録自体に失敗したときは、lico 標準の ldap identity manager を登録します。
|
||||
- トークンを発行するたびに、紐付けを確認する LDAP 検索が 1 回増えます。
|
||||
- lico を更新するときは、`bootstrap.go` を新しい `bsldap.NewIdentityManager` と見比べて追従してください。
|
||||
|
||||
## 既存アカウントとの連携
|
||||
|
||||
サインイン済みのユーザーは、Web のアカウント画面(My Account > Preferences の「Discord」行)から自分のアカウントに Discord を紐付けられます。行が表示されるのは、Discord ログインが有効なときだけです。
|
||||
|
||||
| メソッド | パス | 内容 |
|
||||
|---|---|---|
|
||||
| GET | `/oauth2/discord/account/link` | `{"enabled": bool, "linked": bool}` を返す。無効なときは両方 false |
|
||||
| POST | `/oauth2/discord/account/link` | state Cookie を設定し、Discord の認可 URL を `{"url": ...}` で返す。紐付け済みなら 409、無効なら 404 |
|
||||
|
||||
流れ:
|
||||
|
||||
1. 「Link Discord」を押すと、Web が POST を送ります。ブラウザの遷移ではベアラートークンを送れないので、認可 URL は JSON で受け取り、`window.location.assign` で開きます。
|
||||
2. state Cookie には、通常の項目に加えてモード `link` と、サインイン中のユーザー ID が署名付きで入ります。
|
||||
3. callback では、ログインと同じ順に state、認可コード、サーバー参加を確認します。その後 `GraphProvisioner.Link` で紐付けます。ログオン Cookie は発行しません。
|
||||
4. 結果は `/account?discord_link=<結果>` に戻して伝えます。成功は `linked`、失敗はエラーコードです。Web はメッセージを出してから、このクエリを URL から消します。
|
||||
|
||||
`Link` は次の場合に `ErrIdentityConflict`(`discord_link_conflict`)を返し、アカウントを変更しません。
|
||||
|
||||
- その Discord ID が別のアカウントに紐付いている(無効化されたアカウントも含む)
|
||||
- アカウントが別の Discord ID に紐付いている
|
||||
|
||||
同じ Discord ID に紐付け済みなら、何もせずに成功を返します。表示名やメールは変えません。紐付けの解除はできません。
|
||||
|
||||
## 管理 API と管理画面
|
||||
|
||||
| メソッド | パス | 内容 |
|
||||
|---|---|---|
|
||||
| GET | `/oauth2/discord/admin/settings` | 現在の設定を返す(Client Secret は返さず、`client_secret_set` だけ返す) |
|
||||
| PUT | `/oauth2/discord/admin/settings` | 設定を保存する。`client_secret` を省略するか空にすると、保存済みの値を使い続ける |
|
||||
| GET | `/oauth2/discord/admin/registration` | 登録設定を返す |
|
||||
| PUT | `/oauth2/discord/admin/registration` | 登録設定を保存する(4 項目すべてを送る。未知のキーは 400) |
|
||||
| GET | `/oauth2/discord/admin/pending` | 承認待ちアカウントの一覧を申請の古い順に返す(`{"value": [...]}`) |
|
||||
| POST | `/oauth2/discord/admin/pending/{id}/approve` | アカウントを有効にして承認待ちから外す(204) |
|
||||
| POST | `/oauth2/discord/admin/pending/{id}/reject` | アカウントを削除して承認待ちから外す(204) |
|
||||
|
||||
- proxy は `/oauth2/discord/admin/` と `/oauth2/discord/account/` を認証必須で idp に転送します。それ以外の `/oauth2/discord/` は認証なしで転送します(ルートは先に一致したものが使われるので、この 2 つを先に定義しています)。
|
||||
- idp は proxy が付ける `x-access-token` の reva JWT を検証し、CS3 gateway で `Settings.ReadWrite` 権限を確認します。トークンがない・無効なら 401、権限がなければ 403 です。
|
||||
- 入力は検証します。Client ID とサーバー ID は 15〜21 桁の数字、Client Secret は 256 文字以下で空白を含まないこと、有効にするときは 3 項目すべて必須です。
|
||||
- 設定は `IDP_DISCORD_SETTINGS_FILE`(デフォルト `$OCIS_BASE_DATA_PATH/idp/discord.json`)に権限 0600 で保存します。一時ファイルに書いてからリネームするので、書き込み途中の状態は残りません。保存した値はすぐに反映されます。
|
||||
- 管理画面のセクション(`DiscordSection.vue`)は、`Setting` の `update-all` 権限を持つユーザーにだけ表示します。
|
||||
|
||||
## 新規登録の設定と承認
|
||||
|
||||
管理設定画面の「登録」セクション(`RegistrationSection.vue`)で、次の 4 項目を切り替えます。切り替えた時点で保存し、失敗したら表示を元に戻します。設定は `IDP_DISCORD_SETTINGS_FILE` と同じディレクトリの `registration.json`(デフォルト `$OCIS_BASE_DATA_PATH/idp/registration.json`)に権限 0600 で保存し、すぐに反映されます。
|
||||
|
||||
| 項目 | キー | ファイルがないときの値 | 内容 |
|
||||
|---|---|---|---|
|
||||
| 登録受付 | `allow_registration` | ON | OFF なら Web・Discord どちらの新規登録も受け付けない |
|
||||
| Web 登録 | `allow_web` | OFF | ユーザー名・メール・パスワードのフォームで登録できる |
|
||||
| Discord 登録 | `allow_discord` | ON | アカウントのない Discord ユーザーがユーザー名入力画面から登録できる |
|
||||
| 管理者承認 | `require_approval` | OFF | 新規アカウントを無効の状態で作り、管理者の承認を待つ |
|
||||
|
||||
ファイルがない既存環境では、以前と同じ動作になります。既存アカウントのログインは、これらの設定の影響を受けません。
|
||||
|
||||
### ログイン画面
|
||||
|
||||
- Web 登録が有効(登録受付も ON)のときだけ「アカウント作成」リンクを表示します。リンク先は、OIDC クエリを付けた `/oauth2/discord/register` です。
|
||||
- Discord 登録が有効なときは、Discord ボタンの文言を「Discord でログイン / 登録」にします。
|
||||
- `GET /oauth2/discord/registration`(認証なし)は、同じ判定の結果を `{"web", "discord", "discord_login"}` で返します。ログイン画面はサーバー側でこの判定を使って描画します。
|
||||
|
||||
### Web 登録
|
||||
|
||||
- `GET` / `POST /oauth2/discord/register` で受け付けます。Web 登録が無効なら 403 `registration_closed` です。
|
||||
- POST は、Origin(ない場合は Referer)が `OCIS_URL` と同じオリジンでなければ 403 で拒否します。
|
||||
- 入力は次の条件で検証します。
|
||||
- ユーザー名: Discord 登録と同じルール。
|
||||
- メール: 表示名を含まない単一のアドレスで、254 文字以下。
|
||||
- パスワード: 8〜256 文字で、確認欄と一致すること。
|
||||
- ユーザー名とメールの重複は Graph で確認します。パスワードポリシーは graph サービスの設定で判定されます。Graph が 400 を返し、本文に `password` を含むときは、フォームにエラーを表示します。
|
||||
- 承認が不要な設定なら、有効なアカウントを作ってログイン画面に 303 で戻します。自動ではログインしません。
|
||||
|
||||
### 承認待ち
|
||||
|
||||
- 管理者承認が有効なときは、Web・Discord どちらの登録でも `accountEnabled=false` でアカウントを作ります。同じディレクトリの `pending.json` に、ユーザー ID・ユーザー名・メール・登録元(`web` / `discord`)・申請日時を記録します。セッションは発行せず、「アカウント登録申請を受け付けました」を表示します。
|
||||
- 承認待ちのユーザーが Discord でログインすると、403 `registration_pending` になります。
|
||||
- パスワードログインの場合、lico は無効なアカウントとパスワード違いを区別できません。そこで idp が `/signin/v1/identifier/_/logon` を先に受けます。lico の結果が失敗で、入力したユーザー名(大文字小文字は無視)が承認待ちなら、403 `{"success":false,"error":"registration_pending"}` を返します。ログイン画面には「現在、管理者の承認待ちです」と表示されます。それ以外のリクエストには lico の応答をそのまま返します。
|
||||
- 承認すると `accountEnabled=true` にし、拒否するとアカウントを Graph で削除します。どちらも Graph の操作が成功してから記録を消します。失敗したときは 502 を返し、記録が残るので再試行できます。
|
||||
|
||||
### 制限
|
||||
|
||||
- パスワードログインの承認待ち判定は、パスワードの正誤に関係なく 403 を返します。そのため、あるユーザー名が承認待ちかどうかを第三者が判別できます。
|
||||
- 承認待ち一覧ではなく Users 画面でアカウントを有効にすると、`pending.json` の記録が残ります。パスワードログインはできますが、Discord ログインは遮断されたままです。承認待ち一覧から承認してください。
|
||||
- `pending.json` への記録に失敗すると、アカウントは無効のまま作られ、一覧に出ません(エラーログ `could not record pending account` が出ます)。この場合は Users 画面で有効化または削除します。
|
||||
|
||||
## セキュリティ上の扱い
|
||||
|
||||
| 項目 | 内容 |
|
||||
|---|---|
|
||||
| state Cookie | `__Secure-RC-Discord-State`。HttpOnly、Secure、SameSite=Lax(discord.com からのトップレベル遷移で送るため)、Path `/oauth2/discord/`、有効期限 10 分、callback で必ず削除 |
|
||||
| signup Cookie | `__Secure-RC-Discord-Signup`。HttpOnly、Secure、SameSite=Strict、有効期限 10 分。フォームの hidden トークンと一致しないと受け付けない |
|
||||
| 署名 | HMAC-SHA256。鍵は JWT シークレットから導出するので、idp を複数台動かしても再起動しても進行中のログインは壊れない。state と signup は用途別の接頭辞で署名するので、片方の Cookie をもう片方に流用できない |
|
||||
| HTML | ログイン画面と同じ CSP(nonce 付き)とセキュリティヘッダーを付け、`html/template` でエスケープする |
|
||||
| 入力サイズ | login と register のクエリは 4096 バイト、signup と register のフォームは 8 KiB、logon の本文は 64 KiB まで |
|
||||
| Web 登録の POST | Origin / Referer が `OCIS_URL` と同じオリジンでなければ拒否する |
|
||||
|
||||
## エラー画面
|
||||
|
||||
エラーはログイン画面と同じレイアウトで表示します。Accept-Language が日本語なら日本語、それ以外は英語です。
|
||||
|
||||
| コード | 状況 |
|
||||
|---|---|
|
||||
| `discord_not_member` | 許可サーバーに参加していない(403) |
|
||||
| `discord_disabled` | 機能が無効(404) |
|
||||
| `discord_invalid_state` | state / signup Cookie が不正(400) |
|
||||
| `discord_state_expired` | 10 分を過ぎた(400) |
|
||||
| `discord_invalid_code` | 認可コードが無効(400) |
|
||||
| `discord_cancelled` | Discord で認可を拒否した(403) |
|
||||
| `discord_upstream` | Discord API に接続できない(502) |
|
||||
| `discord_provision_failed` | アカウントの検索・作成に失敗(500) |
|
||||
| `discord_server_error` | その他のサーバーエラー(500) |
|
||||
| `discord_username_invalid` | ユーザー名がルール違反(入力画面で表示) |
|
||||
| `discord_username_taken` | ユーザー名が使用済み(入力画面で表示) |
|
||||
| `discord_link_conflict` | 連携先が別のアカウントまたは別の Discord に紐付いている(アカウント画面で表示) |
|
||||
| `registration_closed` | この経路での新規登録を受け付けていない(403) |
|
||||
| `registration_pending` | アカウントが承認待ち(403) |
|
||||
| `registration_submitted` | 承認制で登録申請を受け付けた(200) |
|
||||
| `registration_mail_invalid` | メールアドレスが不正(登録画面で表示) |
|
||||
| `registration_mail_taken` | メールアドレスが使用済み(登録画面で表示) |
|
||||
| `registration_password_invalid` | パスワードが短い、またはパスワードポリシー違反(登録画面で表示) |
|
||||
| `registration_password_mismatch` | 確認欄と一致しない(登録画面で表示) |
|
||||
|
||||
連携フローでは、state Cookie の検証より後のエラーをエラー画面ではなく、アカウント画面の `discord_link` クエリで返します。
|
||||
|
||||
## 既存アカウントとの互換性
|
||||
|
||||
以前の実装は、ユーザー名 `discord-<Discord ID>` でアカウントを作っていました。これらのアカウントにも identities が入っているので、今の実装でもそのまま紐付け済みアカウントとして見つかります。ユーザー名は変わりません。
|
||||
|
||||
## 未確認の点
|
||||
|
||||
- idp の LDAP bind ユーザー(`uid=idp,ou=sysusers,o=libregraph-idm`)が `oCExternalIdentity` を読めるかどうかは、idm の ACL で確認していません。読めない場合、紐付け済みアカウントが見つからず毎回ユーザー名入力画面が出ます。また `email_verified` も `true` になりません。
|
||||
- 実際の Discord と oCIS を使った通しの動作確認はしていません。
|
||||
|
||||
## ファイル構成
|
||||
|
||||
| パス | 内容 |
|
||||
|---|---|
|
||||
| `services/idp/pkg/discord/handler.go` | ルーティング、login / callback、エラーコード |
|
||||
| `services/idp/pkg/discord/signup.go` | ユーザー名入力フロー |
|
||||
| `services/idp/pkg/discord/link.go` | 既存アカウントとの連携 API とフロー |
|
||||
| `services/idp/pkg/discord/state.go` | state Cookie の署名と検証 |
|
||||
| `services/idp/pkg/discord/client.go` | Discord API クライアント、サーバー参加チェック |
|
||||
| `services/idp/pkg/discord/provision.go` | アカウントの検索・紐付け・作成、ユーザー名ルール |
|
||||
| `services/idp/pkg/discord/ldapidentity.go` | `oCExternalIdentity` の LDAP 直接検索 |
|
||||
| `services/idp/pkg/discord/graph.go` | Graph API(サービスアカウント)経由のユーザー操作 |
|
||||
| `services/idp/pkg/discord/session.go` | lico ログオン Cookie の発行 |
|
||||
| `services/idp/pkg/discord/settings.go` | 設定の検証と保存 |
|
||||
| `services/idp/pkg/discord/admin.go` | 管理 API の認可、連携 API のユーザー認証 |
|
||||
| `services/idp/pkg/discord/registration.go` | 登録設定の保存、公開 API と管理 API |
|
||||
| `services/idp/pkg/discord/pending.go` | 承認待ちアカウントの保存 |
|
||||
| `services/idp/pkg/discord/approval.go` | 承認待ち一覧と承認・拒否の管理 API |
|
||||
| `services/idp/pkg/discord/logon.go` | パスワードログインの承認待ち判定 |
|
||||
| `services/idp/pkg/discord/websignup.go` | Web 登録フォームの処理 |
|
||||
| `services/idp/pkg/service/v0/discord_register.go` | Web 登録画面の描画 |
|
||||
| `services/idp/pkg/backends/ldapverified/` | `email_verified` 用の LDAP バックエンドラッパーと identity manager |
|
||||
| `services/idp/pkg/service/v0/discord.go` | 依存関係の組み立て、画面描画、日英メッセージ |
|
||||
| `services/idp/pkg/service/v0/ldap_manager.go` | ラッパー版 identity manager の登録 |
|
||||
| `services/idp/assets/identifier/discord_signup.html` | ユーザー名入力画面 |
|
||||
| `services/idp/assets/identifier/discord_register.html` | Web 登録画面 |
|
||||
| `services/idp/assets/identifier/index.html`, `static/theme.css` | ログインボタンとスタイル |
|
||||
| `services/proxy/pkg/config/defaults/defaultconfig.go` | `/oauth2/discord/` のルート |
|
||||
| `services/idp/pkg/config/` | `TokenManager`、`ServiceAccount`、`Discord` 設定 |
|
||||
| `ocis/pkg/init/` | `ocis init` でサービスアカウントを idp に書き込む |
|
||||
| `web/packages/web-app-admin-settings/src/components/General/DiscordSection.vue` | 管理設定画面 |
|
||||
| `web/packages/web-app-admin-settings/src/components/General/RegistrationSection.vue` | 登録設定と承認待ち一覧 |
|
||||
| `web/packages/web-runtime/src/components/Account/DiscordLink.vue` | アカウント画面の連携行 |
|
||||
|
||||
テストは `go test ./services/idp/pkg/...` と、`DiscordSection.spec.ts`、`RegistrationSection.spec.ts`、`DiscordLink.spec.ts`(web)で実行できます。
|
||||
@@ -0,0 +1,86 @@
|
||||
// Package eventdedup drops redelivered copies of events.
|
||||
//
|
||||
// JetStream redelivers a message when its ack does not arrive within AckWait.
|
||||
// With reva's event consumers the ack is sent only after a worker takes the
|
||||
// event off the channel, so messages that wait behind a long running task can
|
||||
// be redelivered and processed twice. Every published event carries a unique
|
||||
// event ID (see reva events.Publish), so a redelivered copy has the same ID as
|
||||
// the original and can be recognised.
|
||||
//
|
||||
// The key is the event ID, not the upload ID: a single upload legitimately
|
||||
// produces several distinct events (BytesReceived, StepFinished, ...).
|
||||
package eventdedup
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/owncloud/reva/v2/pkg/events"
|
||||
)
|
||||
|
||||
// Seen remembers event IDs for a limited time.
|
||||
type Seen struct {
|
||||
mu sync.Mutex
|
||||
ttl time.Duration
|
||||
now func() time.Time
|
||||
ids map[string]time.Time
|
||||
lastGC time.Time
|
||||
}
|
||||
|
||||
// NewSeen returns a Seen that forgets IDs after ttl.
|
||||
func NewSeen(ttl time.Duration) *Seen {
|
||||
return &Seen{ttl: ttl, now: time.Now, ids: map[string]time.Time{}}
|
||||
}
|
||||
|
||||
// FirstTime records id and reports whether it was not seen within the ttl.
|
||||
// Empty IDs are always reported as first time, since they cannot be matched.
|
||||
func (s *Seen) FirstTime(id string) bool {
|
||||
if id == "" {
|
||||
return true
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
now := s.now()
|
||||
if now.Sub(s.lastGC) > s.ttl {
|
||||
for k, t := range s.ids {
|
||||
if now.Sub(t) > s.ttl {
|
||||
delete(s.ids, k)
|
||||
}
|
||||
}
|
||||
s.lastGC = now
|
||||
}
|
||||
|
||||
if t, ok := s.ids[id]; ok && now.Sub(t) <= s.ttl {
|
||||
return false
|
||||
}
|
||||
s.ids[id] = now
|
||||
return true
|
||||
}
|
||||
|
||||
// Len returns the number of remembered IDs.
|
||||
func (s *Seen) Len() int {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return len(s.ids)
|
||||
}
|
||||
|
||||
// Filter forwards events from in whose ID was not seen before. onDrop, if not
|
||||
// nil, is called for every dropped duplicate. The returned channel is closed
|
||||
// when in is closed.
|
||||
func Filter(in <-chan events.Event, seen *Seen, onDrop func(events.Event)) <-chan events.Event {
|
||||
out := make(chan events.Event)
|
||||
go func() {
|
||||
defer close(out)
|
||||
for e := range in {
|
||||
if !seen.FirstTime(e.ID) {
|
||||
if onDrop != nil {
|
||||
onDrop(e)
|
||||
}
|
||||
continue
|
||||
}
|
||||
out <- e
|
||||
}
|
||||
}()
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package eventdedup_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-micro/plugins/v4/events/natsjs"
|
||||
"github.com/nats-io/nats-server/v2/server"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/eventdedup"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/natsconsumer"
|
||||
"github.com/owncloud/reva/v2/pkg/events"
|
||||
"github.com/owncloud/reva/v2/pkg/events/stream"
|
||||
)
|
||||
|
||||
func TestSeen(t *testing.T) {
|
||||
s := eventdedup.NewSeen(time.Hour)
|
||||
if !s.FirstTime("a") || s.FirstTime("a") || !s.FirstTime("b") {
|
||||
t.Fatal("unexpected dedup result")
|
||||
}
|
||||
if !s.FirstTime("") || !s.FirstTime("") {
|
||||
t.Fatal("empty IDs must never be dropped")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeenExpires(t *testing.T) {
|
||||
s := eventdedup.NewSeen(50 * time.Millisecond)
|
||||
s.FirstTime("a")
|
||||
time.Sleep(120 * time.Millisecond)
|
||||
if !s.FirstTime("a") {
|
||||
t.Fatal("id should be forgotten after ttl")
|
||||
}
|
||||
if s.Len() != 1 {
|
||||
t.Fatalf("expired ids must be removed, len=%d", s.Len())
|
||||
}
|
||||
}
|
||||
|
||||
// runLongTaskScenario reproduces the production problem against a real
|
||||
// JetStream server. AckWait is short compared to the processing time of one
|
||||
// upload ("big"), and there is a single worker. While "big" is processed, the
|
||||
// reva forwarding goroutine is blocked handing off the first follower, so the
|
||||
// remaining followers stay unacked in the natsjs callback and JetStream
|
||||
// redelivers them. Those redelivered copies carry the same event ID as the
|
||||
// originals. The function returns how often each upload was processed.
|
||||
func runLongTaskScenario(t *testing.T, dedup bool) map[string]int {
|
||||
t.Helper()
|
||||
srv, err := server.NewServer(&server.Options{Host: "127.0.0.1", Port: -1, JetStream: true, StoreDir: t.TempDir(), NoSigs: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
go srv.Start()
|
||||
if !srv.ReadyForConnections(10 * time.Second) {
|
||||
t.Fatal("nats server not ready")
|
||||
}
|
||||
defer srv.Shutdown()
|
||||
|
||||
bus, err := stream.Nats(natsjs.Address(srv.ClientURL()), natsjs.ClusterID("test"), natsjs.SynchronousPublish(true))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ch, err := events.Consume(bus, "postprocessing", events.BytesReceived{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// shorten AckWait on the server so the test finishes in seconds
|
||||
nc, js, err := natsconsumer.Connect(natsconsumer.Connection{Endpoint: srv.ClientURL(), Name: "test"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer nc.Close()
|
||||
if _, err := natsconsumer.Apply(js, events.MainQueueName, "postprocessing", natsconsumer.Settings{AckWait: time.Second}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if dedup {
|
||||
ch = eventdedup.Filter(ch, eventdedup.NewSeen(time.Hour), nil)
|
||||
}
|
||||
|
||||
var mu sync.Mutex
|
||||
counts := map[string]int{}
|
||||
go func() { // a single worker, like a fully occupied worker pool
|
||||
for e := range ch {
|
||||
id := e.Event.(events.BytesReceived).UploadID
|
||||
mu.Lock()
|
||||
counts[id]++
|
||||
mu.Unlock()
|
||||
if id == "big" {
|
||||
time.Sleep(5 * time.Second) // much longer than AckWait
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// "big" occupies the worker; the followers queue up behind it. The first
|
||||
// follower is acked at hand-off, the later ones stay unacked and are
|
||||
// redelivered while the worker is busy.
|
||||
ids := []string{"big", "f0", "f1", "f2", "f3"}
|
||||
for _, id := range ids {
|
||||
if err := events.Publish(context.Background(), bus, events.BytesReceived{UploadID: id}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
time.Sleep(10 * time.Second)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
res := map[string]int{}
|
||||
for k, v := range counts {
|
||||
res[k] = v
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func total(counts map[string]int) int {
|
||||
n := 0
|
||||
for _, v := range counts {
|
||||
n += v
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func TestRedeliveredEventsProcessedTwiceWithoutDedup(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("integration test")
|
||||
}
|
||||
counts := runLongTaskScenario(t, false)
|
||||
// 5 distinct uploads; any duplicate from redelivery pushes the total above 5.
|
||||
if total(counts) <= len(counts) {
|
||||
t.Fatalf("expected redelivered events to be processed more than once, counts=%v", counts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedeliveredEventsProcessedOnceWithDedup(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("integration test")
|
||||
}
|
||||
counts := runLongTaskScenario(t, true)
|
||||
var dupes []string
|
||||
for id, c := range counts {
|
||||
if c != 1 {
|
||||
dupes = append(dupes, fmt.Sprintf("%s=%d", id, c))
|
||||
}
|
||||
}
|
||||
if len(dupes) > 0 {
|
||||
t.Fatalf("each upload must be processed exactly once, duplicates: %v (counts=%v)", dupes, counts)
|
||||
}
|
||||
if len(counts) != 5 {
|
||||
t.Fatalf("all 5 uploads should be processed once, counts=%v", counts)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
// Package natsconsumer adjusts the settings of durable JetStream consumers that
|
||||
// were created by other components (for example reva's event consumers).
|
||||
//
|
||||
// The go-micro natsjs plugin used by reva creates its consumers with the server
|
||||
// defaults (AckWait 30s, unlimited MaxDeliver) and does not expose these options.
|
||||
// Passing them as subscribe options would break restarts, because nats.go rejects
|
||||
// a subscription whose options differ from the existing durable consumer.
|
||||
// Updating the consumer on the server avoids that: the client never sends
|
||||
// AckWait or MaxDeliver, so the server-side values survive restarts.
|
||||
package natsconsumer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
)
|
||||
|
||||
// Settings are the consumer settings to enforce. Zero values leave the current
|
||||
// server value untouched.
|
||||
type Settings struct {
|
||||
// AckWait is how long the server waits for an ack before redelivering.
|
||||
AckWait time.Duration
|
||||
// MaxDeliver is the maximum number of delivery attempts. -1 means unlimited.
|
||||
MaxDeliver int
|
||||
}
|
||||
|
||||
// IsZero reports whether no setting is requested.
|
||||
func (s Settings) IsZero() bool {
|
||||
return s.AckWait == 0 && s.MaxDeliver == 0
|
||||
}
|
||||
|
||||
// Validate checks the settings for values the server would reject.
|
||||
func (s Settings) Validate() error {
|
||||
if s.AckWait < 0 {
|
||||
return fmt.Errorf("ack wait must not be negative, got %s", s.AckWait)
|
||||
}
|
||||
if s.MaxDeliver < -1 {
|
||||
return fmt.Errorf("max deliver must be -1 (unlimited), 0 (unchanged) or positive, got %d", s.MaxDeliver)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Connection holds what is needed to reach the NATS server.
|
||||
type Connection struct {
|
||||
Endpoint string
|
||||
Name string
|
||||
EnableTLS bool
|
||||
TLSInsecure bool
|
||||
TLSRootCACertificate string
|
||||
AuthUsername string
|
||||
AuthPassword string
|
||||
}
|
||||
|
||||
// Connect opens a NATS connection and a JetStream context.
|
||||
func Connect(c Connection) (*nats.Conn, nats.JetStreamContext, error) {
|
||||
opts := []nats.Option{nats.Name(c.Name)}
|
||||
if c.AuthUsername != "" || c.AuthPassword != "" {
|
||||
opts = append(opts, nats.UserInfo(c.AuthUsername, c.AuthPassword))
|
||||
}
|
||||
if c.EnableTLS {
|
||||
tlsConf := &tls.Config{
|
||||
MinVersion: tls.VersionTLS12,
|
||||
InsecureSkipVerify: c.TLSInsecure, //nolint:gosec
|
||||
}
|
||||
if c.TLSRootCACertificate != "" {
|
||||
pem, err := os.ReadFile(c.TLSRootCACertificate)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
pool := x509.NewCertPool()
|
||||
if !pool.AppendCertsFromPEM(pem) {
|
||||
return nil, nil, errors.New("failed to append cert from PEM")
|
||||
}
|
||||
tlsConf.RootCAs = pool
|
||||
tlsConf.InsecureSkipVerify = false
|
||||
}
|
||||
opts = append(opts, nats.Secure(tlsConf))
|
||||
}
|
||||
|
||||
nc, err := nats.Connect(c.Endpoint, opts...)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
js, err := nc.JetStream()
|
||||
if err != nil {
|
||||
nc.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
return nc, js, nil
|
||||
}
|
||||
|
||||
// Apply updates the consumer when its settings differ from s. It reports
|
||||
// whether an update was sent.
|
||||
func Apply(js nats.JetStreamManager, stream, consumer string, s Settings) (bool, error) {
|
||||
if err := s.Validate(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
info, err := js.ConsumerInfo(stream, consumer)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
cfg := info.Config
|
||||
changed := false
|
||||
if s.AckWait > 0 && cfg.AckWait != s.AckWait {
|
||||
if len(cfg.BackOff) > 0 {
|
||||
return false, fmt.Errorf("consumer %s/%s uses a backoff list, which overrides ack wait", stream, consumer)
|
||||
}
|
||||
cfg.AckWait = s.AckWait
|
||||
changed = true
|
||||
}
|
||||
if s.MaxDeliver != 0 && cfg.MaxDeliver != s.MaxDeliver {
|
||||
cfg.MaxDeliver = s.MaxDeliver
|
||||
changed = true
|
||||
}
|
||||
if !changed {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if _, err := js.UpdateConsumer(stream, &cfg); err != nil {
|
||||
return false, fmt.Errorf("updating consumer %s/%s: %w", stream, consumer, err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Ensure connects to NATS and applies s to the consumer. It retries every
|
||||
// retryInterval while the stream or consumer does not exist yet, until ctx is done.
|
||||
func Ensure(ctx context.Context, logger log.Logger, conn Connection, stream, consumer string, s Settings, retryInterval time.Duration) error {
|
||||
if s.IsZero() {
|
||||
return nil
|
||||
}
|
||||
if err := s.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
nc, js, err := Connect(conn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer nc.Close()
|
||||
|
||||
for {
|
||||
updated, err := Apply(js, stream, consumer, s)
|
||||
switch {
|
||||
case err == nil:
|
||||
ev := logger.Debug()
|
||||
msg := "NATS consumer settings already up to date"
|
||||
if updated {
|
||||
ev = logger.Info()
|
||||
msg = "updated NATS consumer settings"
|
||||
}
|
||||
ev.Str("stream", stream).Str("consumer", consumer).
|
||||
Str("ackWait", s.AckWait.String()).Int("maxDeliver", s.MaxDeliver).Msg(msg)
|
||||
return nil
|
||||
case errors.Is(err, nats.ErrConsumerNotFound), errors.Is(err, nats.ErrStreamNotFound):
|
||||
// the owning component has not subscribed yet
|
||||
default:
|
||||
return err
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return fmt.Errorf("consumer %s/%s not found: %w", stream, consumer, ctx.Err())
|
||||
case <-time.After(retryInterval):
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package natsconsumer_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats-server/v2/server"
|
||||
"github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/natsconsumer"
|
||||
)
|
||||
|
||||
func runServer(t *testing.T) string {
|
||||
t.Helper()
|
||||
s, err := server.NewServer(&server.Options{Host: "127.0.0.1", Port: -1, JetStream: true, StoreDir: t.TempDir(), NoSigs: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
go s.Start()
|
||||
if !s.ReadyForConnections(10 * time.Second) {
|
||||
t.Fatal("nats server not ready")
|
||||
}
|
||||
t.Cleanup(s.Shutdown)
|
||||
return s.ClientURL()
|
||||
}
|
||||
|
||||
// subscribeLikeNatsjs subscribes with exactly the options the go-micro natsjs
|
||||
// plugin uses (no AckWait, no MaxDeliver).
|
||||
func subscribeLikeNatsjs(t *testing.T, url string) *nats.Conn {
|
||||
t.Helper()
|
||||
nc, err := nats.Connect(url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
js, err := nc.JetStream()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := js.StreamInfo("main-queue"); err != nil {
|
||||
if _, err := js.AddStream(&nats.StreamConfig{Name: "main-queue"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
_, err = js.QueueSubscribe("main-queue", "dcfs", func(*nats.Msg) {},
|
||||
nats.AckExplicit(), nats.DeliverNew(), nats.Durable("dcfs"))
|
||||
if err != nil {
|
||||
t.Fatalf("subscribe: %v", err)
|
||||
}
|
||||
return nc
|
||||
}
|
||||
|
||||
func TestApplyUpdatesConsumerAndSurvivesRestart(t *testing.T) {
|
||||
url := runServer(t)
|
||||
nc := subscribeLikeNatsjs(t, url)
|
||||
|
||||
cnc, js, err := natsconsumer.Connect(natsconsumer.Connection{Endpoint: url, Name: "test"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer cnc.Close()
|
||||
|
||||
want := natsconsumer.Settings{AckWait: 30 * time.Minute, MaxDeliver: 3}
|
||||
updated, err := natsconsumer.Apply(js, "main-queue", "dcfs", want)
|
||||
if err != nil || !updated {
|
||||
t.Fatalf("Apply: updated=%v err=%v", updated, err)
|
||||
}
|
||||
if updated, err := natsconsumer.Apply(js, "main-queue", "dcfs", want); err != nil || updated {
|
||||
t.Fatalf("second Apply should be a no-op: updated=%v err=%v", updated, err)
|
||||
}
|
||||
|
||||
// Simulate a service restart: the durable stays, the client resubscribes
|
||||
// with the natsjs options. This must not fail with a config mismatch.
|
||||
nc.Close()
|
||||
nc2 := subscribeLikeNatsjs(t, url)
|
||||
defer nc2.Close()
|
||||
|
||||
info, err := js.ConsumerInfo("main-queue", "dcfs")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Config.AckWait != want.AckWait || info.Config.MaxDeliver != want.MaxDeliver {
|
||||
t.Fatalf("got AckWait=%s MaxDeliver=%d", info.Config.AckWait, info.Config.MaxDeliver)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureWaitsForConsumer(t *testing.T) {
|
||||
url := runServer(t)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- natsconsumer.Ensure(ctx, log.NopLogger(), natsconsumer.Connection{Endpoint: url, Name: "test"},
|
||||
"main-queue", "dcfs", natsconsumer.Settings{AckWait: 10 * time.Minute, MaxDeliver: 2}, 100*time.Millisecond)
|
||||
}()
|
||||
|
||||
time.Sleep(500 * time.Millisecond) // the consumer appears after Ensure starts
|
||||
nc := subscribeLikeNatsjs(t, url)
|
||||
defer nc.Close()
|
||||
|
||||
if err := <-done; err != nil {
|
||||
t.Fatalf("Ensure: %v", err)
|
||||
}
|
||||
js, _ := nc.JetStream()
|
||||
info, err := js.ConsumerInfo("main-queue", "dcfs")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Config.AckWait != 10*time.Minute || info.Config.MaxDeliver != 2 {
|
||||
t.Fatalf("got AckWait=%s MaxDeliver=%d", info.Config.AckWait, info.Config.MaxDeliver)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidate(t *testing.T) {
|
||||
if err := (natsconsumer.Settings{MaxDeliver: -2}).Validate(); err == nil {
|
||||
t.Fatal("expected error for MaxDeliver -2")
|
||||
}
|
||||
if err := (natsconsumer.Settings{AckWait: -time.Second}).Validate(); err == nil {
|
||||
t.Fatal("expected error for negative AckWait")
|
||||
}
|
||||
}
|
||||
@@ -173,10 +173,11 @@ func CreateConfig(insecure, forceOverwrite, diff bool, configPath, adminPassword
|
||||
IdmPassword: idmServicePassword,
|
||||
},
|
||||
},
|
||||
Idp: LdapBasedService{
|
||||
Idp: IdpService{
|
||||
Ldap: LdapSettings{
|
||||
BindPassword: idpServicePassword,
|
||||
},
|
||||
ServiceAccount: serviceAccount,
|
||||
},
|
||||
AuthBasic: AuthbasicService{
|
||||
AuthProviders: LdapBasedService{
|
||||
|
||||
@@ -22,7 +22,7 @@ type OcisConfig struct {
|
||||
SystemUserID string `yaml:"system_user_id"`
|
||||
AdminUserID string `yaml:"admin_user_id"`
|
||||
Graph GraphService `yaml:"graph"`
|
||||
Idp LdapBasedService `yaml:"idp"`
|
||||
Idp IdpService `yaml:"idp"`
|
||||
Idm IdmService `yaml:"idm"`
|
||||
Collaboration Collaboration `yaml:"collaboration"`
|
||||
Proxy ProxyService `yaml:"proxy"`
|
||||
@@ -145,6 +145,12 @@ type LdapBasedService struct {
|
||||
Ldap LdapSettings
|
||||
}
|
||||
|
||||
// IdpService is the configuration for the idp service
|
||||
type IdpService struct {
|
||||
Ldap LdapSettings
|
||||
ServiceAccount ServiceAccount `yaml:"service_account"`
|
||||
}
|
||||
|
||||
// LdapSettings is the configuration for LDAP settings
|
||||
type LdapSettings struct {
|
||||
BindPassword string `yaml:"bind_password"`
|
||||
|
||||
@@ -289,6 +289,7 @@ func NewService(ctx context.Context, options ...Option) (*Service, error) {
|
||||
reg(3, opts.Config.IDP.Service.Name, func(ctx context.Context, cfg *ociscfg.Config) error {
|
||||
cfg.IDP.Context = ctx
|
||||
cfg.IDP.Commons = cfg.Commons
|
||||
idpServiceAccountFallback(cfg)
|
||||
return runServerCommand(ctx, idp.Server(cfg.IDP))
|
||||
})
|
||||
reg(3, opts.Config.Proxy.Service.Name, func(ctx context.Context, cfg *ociscfg.Config) error {
|
||||
@@ -619,3 +620,18 @@ func newRPCServer(s *Service) (*http.Server, error) {
|
||||
}
|
||||
return srv, nil
|
||||
}
|
||||
|
||||
// idpServiceAccountFallback copies the graph service account to the idp when
|
||||
// the idp has none. Configs created before `ocis init` wrote
|
||||
// idp.service_account only have it in the graph section.
|
||||
func idpServiceAccountFallback(cfg *ociscfg.Config) {
|
||||
if cfg.IDP == nil || cfg.Graph == nil {
|
||||
return
|
||||
}
|
||||
sa := &cfg.IDP.ServiceAccount
|
||||
if sa.ServiceAccountID != "" || sa.ServiceAccountSecret != "" {
|
||||
return
|
||||
}
|
||||
sa.ServiceAccountID = cfg.Graph.ServiceAccount.ServiceAccountID
|
||||
sa.ServiceAccountSecret = cfg.Graph.ServiceAccount.ServiceAccountSecret
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
[main]
|
||||
host = https://www.transifex.com
|
||||
|
||||
[o:owncloud-org:p:owncloud-web:r:ocis-activitylog]
|
||||
file_filter = locale/<lang>/LC_MESSAGES/activitylog.po
|
||||
minimum_perc = 75
|
||||
resource_name = ocis-activitylog
|
||||
source_file = activitylog.pot
|
||||
source_lang = en
|
||||
type = PO
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
[main]
|
||||
host = https://www.transifex.com
|
||||
|
||||
[o:owncloud-org:p:owncloud-web:r:ocis-graph]
|
||||
file_filter = locale/<lang>/LC_MESSAGES/graph.po
|
||||
minimum_perc = 75
|
||||
resource_name = ocis-graph
|
||||
source_file = graph.pot
|
||||
source_lang = en
|
||||
type = PO
|
||||
@@ -566,7 +566,7 @@ func (g Graph) updateDrive(w http.ResponseWriter, r *http.Request, apiVersion AP
|
||||
}
|
||||
|
||||
if _, ok := drive.GetNameOk(); ok {
|
||||
spacename := strings.TrimSpace(drive.GetName())
|
||||
spacename := sanitizeSpaceName(drive.GetName())
|
||||
if err := validateSpaceName(spacename); err != nil {
|
||||
logger.Info().Err(err).Msg("could not update drive: spacename invalid")
|
||||
errorcode.GeneralException.Render(w, r, http.StatusBadRequest, err.Error())
|
||||
|
||||
@@ -123,6 +123,27 @@ func TestSort(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeSpaceName(t *testing.T) {
|
||||
testCases := []struct {
|
||||
Alias string
|
||||
Input string
|
||||
Expected string
|
||||
}{
|
||||
{"slash and spaces", "User / Name", "User _ Name"},
|
||||
{"all forbidden", `/ \ . : ? * " > < |`, "_ _ _ _ _ _ _ _ _ _"},
|
||||
{"trim", " Alice ", "Alice"},
|
||||
{"safe name", "Alice", "Alice"},
|
||||
{"empty", " ", ""},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
require.Equal(t, tc.Expected, sanitizeSpaceName(tc.Input), tc.Alias)
|
||||
if tc.Expected != "" {
|
||||
require.NoError(t, validateSpaceName(sanitizeSpaceName(tc.Input)), tc.Alias)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSpaceNameValidation(t *testing.T) {
|
||||
// set max length
|
||||
_maxSpaceNameLength = 10
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package svc
|
||||
|
||||
import "strings"
|
||||
|
||||
const spaceNameReplacement = "_"
|
||||
|
||||
func sanitizeSpaceName(name string) string {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
return ""
|
||||
}
|
||||
for _, c := range _invalidSpaceNameCharacters {
|
||||
name = strings.ReplaceAll(name, c, spaceNameReplacement)
|
||||
}
|
||||
name = strings.Join(strings.Fields(name), " ")
|
||||
return strings.TrimSpace(name)
|
||||
}
|
||||
@@ -30,6 +30,7 @@ import (
|
||||
ocissettingssvc "github.com/owncloud/ocis/v2/services/settings/pkg/service/v0"
|
||||
"github.com/owncloud/ocis/v2/services/settings/pkg/store/defaults"
|
||||
revactx "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
"github.com/owncloud/reva/v2/pkg/events"
|
||||
"github.com/owncloud/reva/v2/pkg/rgrpc/status"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
@@ -513,6 +514,10 @@ func (g Graph) PostUser(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := g.ensurePersonalSpace(r.Context(), u); err != nil {
|
||||
logger.Error().Err(err).Str("id", u.GetId()).Msg("could not provision personal space")
|
||||
}
|
||||
|
||||
// assign roles if possible
|
||||
if g.roleService != nil && g.config.API.AssignDefaultUserRole {
|
||||
// All users get the user role by default currently.
|
||||
@@ -1058,9 +1063,134 @@ func (g Graph) patchUser(w http.ResponseWriter, r *http.Request, nameOrID string
|
||||
}
|
||||
|
||||
u.PreferredLanguage = preferredLanguage
|
||||
|
||||
if _, ok := changes.GetDisplayNameOk(); ok {
|
||||
if err := g.syncPersonalSpaceName(r.Context(), u); err != nil {
|
||||
logger.Error().Err(err).Str("id", u.GetId()).Msg("could not sync personal space name")
|
||||
errorcode.GeneralException.Render(w, r, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
g.patchUserResponse(w, r, u, features)
|
||||
}
|
||||
|
||||
func (g Graph) syncPersonalSpaceName(ctx context.Context, user *libregraph.User) error {
|
||||
if user == nil || user.GetId() == "" {
|
||||
return nil
|
||||
}
|
||||
spaceName := sanitizeSpaceName(user.GetDisplayName())
|
||||
if err := validateSpaceName(spaceName); err != nil {
|
||||
return fmt.Errorf("invalid spacename: %s", err.Error())
|
||||
}
|
||||
|
||||
client, err := g.gatewaySelector.Next()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
spaces, err := client.ListStorageSpaces(ctx, &storageprovider.ListStorageSpacesRequest{
|
||||
Opaque: utils.AppendPlainToOpaque(nil, "unrestricted", "T"),
|
||||
Filters: []*storageprovider.ListStorageSpacesRequest_Filter{
|
||||
listStorageSpacesUserFilter(user.GetId()),
|
||||
listStorageSpacesTypeFilter(_spaceTypePersonal),
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch spaces.GetStatus().GetCode() {
|
||||
case cs3rpc.Code_CODE_OK:
|
||||
case cs3rpc.Code_CODE_NOT_FOUND:
|
||||
return g.ensurePersonalSpace(ctx, user)
|
||||
default:
|
||||
return fmt.Errorf("%s", spaces.GetStatus().GetMessage())
|
||||
}
|
||||
if len(spaces.GetStorageSpaces()) == 0 {
|
||||
return g.ensurePersonalSpace(ctx, user)
|
||||
}
|
||||
|
||||
sp := spaces.GetStorageSpaces()[0]
|
||||
if sp.GetName() == spaceName {
|
||||
return nil
|
||||
}
|
||||
resp, err := client.UpdateStorageSpace(ctx, &storageprovider.UpdateStorageSpaceRequest{
|
||||
StorageSpace: &storageprovider.StorageSpace{
|
||||
Id: &storageprovider.StorageSpaceId{OpaqueId: sp.GetId().GetOpaqueId()},
|
||||
Root: sp.GetRoot(),
|
||||
Name: spaceName,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.GetStatus().GetCode() != cs3rpc.Code_CODE_OK {
|
||||
return fmt.Errorf("%s", resp.GetStatus().GetMessage())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g Graph) ensurePersonalSpace(ctx context.Context, user *libregraph.User) error {
|
||||
if user == nil || user.GetId() == "" {
|
||||
return nil
|
||||
}
|
||||
spaceName := sanitizeSpaceName(user.GetDisplayName())
|
||||
if spaceName == "" {
|
||||
spaceName = sanitizeSpaceName(user.GetOnPremisesSamAccountName())
|
||||
}
|
||||
if err := validateSpaceName(spaceName); err != nil {
|
||||
return fmt.Errorf("invalid spacename: %s", err.Error())
|
||||
}
|
||||
|
||||
client, err := g.gatewaySelector.Next()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
existing, err := client.ListStorageSpaces(ctx, &storageprovider.ListStorageSpacesRequest{
|
||||
Opaque: utils.AppendPlainToOpaque(nil, "unrestricted", "T"),
|
||||
Filters: []*storageprovider.ListStorageSpacesRequest_Filter{
|
||||
listStorageSpacesUserFilter(user.GetId()),
|
||||
listStorageSpacesTypeFilter(_spaceTypePersonal),
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if existing.GetStatus().GetCode() == cs3rpc.Code_CODE_OK && len(existing.GetStorageSpaces()) > 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
owner := &userv1beta1.User{
|
||||
Id: &userv1beta1.UserId{
|
||||
OpaqueId: user.GetId(),
|
||||
},
|
||||
Username: user.GetOnPremisesSamAccountName(),
|
||||
DisplayName: spaceName,
|
||||
}
|
||||
if current, ok := revactx.ContextGetUser(ctx); ok && current.GetId().GetOpaqueId() == user.GetId() {
|
||||
owner = current
|
||||
owner.DisplayName = spaceName
|
||||
}
|
||||
|
||||
spaceCtx := revactx.ContextSetUser(ctx, owner)
|
||||
resp, err := client.CreateStorageSpace(spaceCtx, &storageprovider.CreateStorageSpaceRequest{
|
||||
Type: _spaceTypePersonal,
|
||||
Name: spaceName,
|
||||
Owner: owner,
|
||||
Opaque: utils.AppendPlainToOpaque(nil, "space_id", user.GetId()),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch resp.GetStatus().GetCode() {
|
||||
case cs3rpc.Code_CODE_OK, cs3rpc.Code_CODE_ALREADY_EXISTS:
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("%s", resp.GetStatus().GetMessage())
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Graph) patchUserResponse(w http.ResponseWriter, r *http.Request, user *libregraph.User, features []events.UserFeature) {
|
||||
e := events.UserFeatureChanged{
|
||||
UserID: *user.Id,
|
||||
|
||||
@@ -1328,6 +1328,93 @@ var _ = Describe("Users", func() {
|
||||
Expect(rr.Code).To(Equal(http.StatusBadRequest))
|
||||
})
|
||||
|
||||
It("syncs a personal space name that contains forbidden characters", func() {
|
||||
user.SetDisplayName("User / Name")
|
||||
user.SetId("user-id")
|
||||
user.SetOnPremisesSamAccountName("missan")
|
||||
|
||||
userUpdate.SetDisplayName("User / Name")
|
||||
expectedUser.SetDisplayName("User / Name")
|
||||
expectedUser.SetId(user.GetId())
|
||||
expectedUser.SetOnPremisesSamAccountName("missan")
|
||||
|
||||
permissionService.On("GetPermissionByID", mock.Anything, mock.Anything).Return(&settings.GetPermissionByIDResponse{
|
||||
Permission: &settingsmsg.Permission{
|
||||
Constraint: settingsmsg.Permission_CONSTRAINT_ALL,
|
||||
},
|
||||
}, nil)
|
||||
identityBackend.On("UpdateUser", mock.Anything, user.GetId(), mock.Anything).Return(expectedUser, nil)
|
||||
gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(&provider.ListStorageSpacesResponse{
|
||||
Status: status.NewOK(ctx),
|
||||
StorageSpaces: []*provider.StorageSpace{{
|
||||
Id: &provider.StorageSpaceId{OpaqueId: "space-id"},
|
||||
Name: "User / Name",
|
||||
Root: &provider.ResourceId{StorageId: "pro-1", SpaceId: "space-id", OpaqueId: "space-id"},
|
||||
}},
|
||||
}, nil)
|
||||
gatewayClient.On("UpdateStorageSpace", mock.Anything, mock.Anything).Return(&provider.UpdateStorageSpaceResponse{
|
||||
Status: status.NewOK(ctx),
|
||||
StorageSpace: &provider.StorageSpace{
|
||||
Id: &provider.StorageSpaceId{OpaqueId: "space-id"},
|
||||
Name: "User _ Name",
|
||||
Root: &provider.ResourceId{StorageId: "pro-1", SpaceId: "space-id", OpaqueId: "space-id"},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
data, err := json.Marshal(userUpdate)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
r := httptest.NewRequest(http.MethodPost, "/graph/v1.0/users", bytes.NewBuffer(data))
|
||||
rctx := chi.NewRouteContext()
|
||||
rctx.URLParams.Add("userID", user.GetId())
|
||||
r = r.WithContext(context.WithValue(revactx.ContextSetUser(ctx, currentUser), chi.RouteCtxKey, rctx))
|
||||
svc.PatchUser(rr, r)
|
||||
|
||||
Expect(rr.Code).To(Equal(http.StatusOK))
|
||||
gatewayClient.AssertCalled(GinkgoT(), "UpdateStorageSpace", mock.Anything, mock.MatchedBy(func(req *provider.UpdateStorageSpaceRequest) bool {
|
||||
return req.GetStorageSpace().GetName() == "User _ Name"
|
||||
}))
|
||||
})
|
||||
|
||||
It("creates a missing personal space with a sanitized name", func() {
|
||||
user.SetDisplayName("User / Name")
|
||||
user.SetId("user-id")
|
||||
user.SetOnPremisesSamAccountName("missan")
|
||||
|
||||
userUpdate.SetDisplayName("User / Name")
|
||||
expectedUser.SetDisplayName("User / Name")
|
||||
expectedUser.SetId(user.GetId())
|
||||
expectedUser.SetOnPremisesSamAccountName("missan")
|
||||
|
||||
permissionService.On("GetPermissionByID", mock.Anything, mock.Anything).Return(&settings.GetPermissionByIDResponse{
|
||||
Permission: &settingsmsg.Permission{
|
||||
Constraint: settingsmsg.Permission_CONSTRAINT_ALL,
|
||||
},
|
||||
}, nil)
|
||||
identityBackend.On("UpdateUser", mock.Anything, user.GetId(), mock.Anything).Return(expectedUser, nil)
|
||||
gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(&provider.ListStorageSpacesResponse{
|
||||
Status: status.NewOK(ctx),
|
||||
StorageSpaces: []*provider.StorageSpace{},
|
||||
}, nil)
|
||||
gatewayClient.On("CreateStorageSpace", mock.Anything, mock.Anything).Return(&provider.CreateStorageSpaceResponse{
|
||||
Status: status.NewOK(ctx),
|
||||
}, nil)
|
||||
|
||||
data, err := json.Marshal(userUpdate)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
r := httptest.NewRequest(http.MethodPost, "/graph/v1.0/users", bytes.NewBuffer(data))
|
||||
rctx := chi.NewRouteContext()
|
||||
rctx.URLParams.Add("userID", user.GetId())
|
||||
r = r.WithContext(context.WithValue(revactx.ContextSetUser(ctx, currentUser), chi.RouteCtxKey, rctx))
|
||||
svc.PatchUser(rr, r)
|
||||
|
||||
Expect(rr.Code).To(Equal(http.StatusOK))
|
||||
gatewayClient.AssertCalled(GinkgoT(), "CreateStorageSpace", mock.Anything, mock.MatchedBy(func(req *provider.CreateStorageSpaceRequest) bool {
|
||||
return req.GetType() == "personal" && req.GetName() == "User _ Name"
|
||||
}))
|
||||
})
|
||||
|
||||
It("updates attributes", func() {
|
||||
userUpdate.SetMail("mail@mail.test")
|
||||
userUpdate.SetDisplayName("New Display Name")
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="{{.Lang}}">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="theme-color" content="#1b223d">
|
||||
<title>{{.Title}}</title>
|
||||
<link rel="icon" href="{{.PathPrefix}}/static/favicon.ico">
|
||||
<link rel="stylesheet" href="{{.PathPrefix}}/static/theme.css">
|
||||
<style nonce="{{.Nonce}}">{{if .BgImgURL}}body.oc-login-bg{background-image:url('{{.BgImgURL}}')}{{end}}</style>
|
||||
</head>
|
||||
<body class="oc-login-bg">
|
||||
<main>
|
||||
<div class="oc-login-form">
|
||||
<img class="oc-logo" src="{{.LogoURL}}" alt="ownCloud">
|
||||
<h1 class="oc-invisible-sr">{{.Headline}}</h1>
|
||||
<form id="register-form" method="post" action="{{.Action}}">
|
||||
<p class="oc-message">{{.Intro}}</p>
|
||||
<input type="hidden" name="q" value="{{.Query}}">
|
||||
<div>
|
||||
<label class="oc-label" for="register-username">{{.LabelUsername}}</label>
|
||||
<input class="oc-input{{if eq .ErrField "username"}} error{{end}}" type="text" id="register-username" name="username" value="{{.Username}}" autocomplete="username" autocapitalize="none" spellcheck="false" required minlength="3" maxlength="32" aria-describedby="register-username-hint" autofocus>
|
||||
<p id="register-username-hint" class="oc-hint">{{.HintUsername}}</p>
|
||||
</div>
|
||||
<div>
|
||||
<label class="oc-label" for="register-mail">{{.LabelMail}}</label>
|
||||
<input class="oc-input{{if eq .ErrField "mail"}} error{{end}}" type="email" id="register-mail" name="mail" value="{{.Mail}}" autocomplete="email" required maxlength="254">
|
||||
</div>
|
||||
<div>
|
||||
<label class="oc-label" for="register-password">{{.LabelPassword}}</label>
|
||||
<input class="oc-input{{if eq .ErrField "password"}} error{{end}}" type="password" id="register-password" name="password" autocomplete="new-password" required minlength="8" maxlength="256" aria-describedby="register-password-hint">
|
||||
<p id="register-password-hint" class="oc-hint">{{.HintPassword}}</p>
|
||||
</div>
|
||||
<div>
|
||||
<label class="oc-label" for="register-password-confirm">{{.LabelConfirm}}</label>
|
||||
<input class="oc-input{{if eq .ErrField "password"}} error{{end}}" type="password" id="register-password-confirm" name="password_confirm" autocomplete="new-password" required minlength="8" maxlength="256">
|
||||
{{if .Error}}<p id="register-error" class="oc-error-message" role="alert">{{.Error}}</p>{{end}}
|
||||
</div>
|
||||
<div>
|
||||
<button class="oc-button-primary" type="submit" id="register-btn">{{.Button}}</button>
|
||||
</div>
|
||||
</form>
|
||||
<p><a href="{{.LoginURL}}">{{.BackLabel}}</a></p>
|
||||
</div>
|
||||
</main>
|
||||
<footer class="oc-footer-message">ownCloud - a safe home for all your data</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,34 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="{{.Lang}}">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="theme-color" content="#1b223d">
|
||||
<title>{{.Title}}</title>
|
||||
<link rel="icon" href="{{.PathPrefix}}/static/favicon.ico">
|
||||
<link rel="stylesheet" href="{{.PathPrefix}}/static/theme.css">
|
||||
<style nonce="{{.Nonce}}">{{if .BgImgURL}}body.oc-login-bg{background-image:url('{{.BgImgURL}}')}{{end}}</style>
|
||||
</head>
|
||||
<body class="oc-login-bg">
|
||||
<main>
|
||||
<div class="oc-login-form">
|
||||
<img class="oc-logo" src="{{.LogoURL}}" alt="ownCloud">
|
||||
<h1 class="oc-invisible-sr">{{.Headline}}</h1>
|
||||
<form id="discord-signup-form" method="post" action="{{.Action}}">
|
||||
<p class="oc-message">{{.Intro}}</p>
|
||||
<input type="hidden" name="token" value="{{.Token}}">
|
||||
<div>
|
||||
<label class="oc-label" for="discord-signup-username">{{.LabelUsername}}</label>
|
||||
<input class="oc-input{{if .Error}} error{{end}}" type="text" id="discord-signup-username" name="username" value="{{.Username}}" autocomplete="username" autocapitalize="none" spellcheck="false" required minlength="3" maxlength="32" aria-describedby="discord-signup-hint{{if .Error}} discord-signup-error{{end}}" autofocus>
|
||||
<p id="discord-signup-hint" class="oc-hint">{{.Hint}}</p>
|
||||
{{if .Error}}<p id="discord-signup-error" class="oc-error-message" role="alert">{{.Error}}</p>{{end}}
|
||||
</div>
|
||||
<div>
|
||||
<button class="oc-button-primary" type="submit" id="discord-signup-btn">{{.Button}}</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</main>
|
||||
<footer class="oc-footer-message">ownCloud - a safe home for all your data</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -19,6 +19,7 @@
|
||||
data-msg-invalid="{{.ErrInvalid}}"
|
||||
data-msg-failed="{{.ErrFailed}}"
|
||||
data-msg-default="{{.ErrDefault}}"
|
||||
data-msg-pending="{{.ErrPending}}"
|
||||
data-msg-signing-in="{{.ButtonSigningIn}}"
|
||||
data-msg-sign-in="{{.ButtonSignIn}}">
|
||||
<div>
|
||||
@@ -34,7 +35,12 @@
|
||||
<button class="oc-button-primary" type="submit" id="submit-btn">{{.ButtonSignIn}}</button>
|
||||
</div>
|
||||
</form>
|
||||
{{if .DiscordLoginURL}}<div id="oc-discord-login" class="oc-discord-login" hidden>
|
||||
<p class="oc-login-or"><span>{{.OrLabel}}</span></p>
|
||||
<a class="oc-button-primary oc-button-discord" id="discord-login-btn" href="{{.DiscordLoginURL}}">{{.DiscordLabel}}</a>
|
||||
</div>{{end}}
|
||||
{{if .PasswordResetURI}}<p><a href="{{.PasswordResetURI}}">{{.ResetLabel}}</a></p>{{end}}
|
||||
{{if .RegisterURL}}<p id="oc-register-link" hidden><a href="{{.RegisterURL}}">{{.RegisterLabel}}</a></p>{{end}}
|
||||
</div>
|
||||
</main>
|
||||
<footer class="oc-footer-message">ownCloud - a safe home for all your data</footer>
|
||||
@@ -48,6 +54,7 @@
|
||||
var MSG_INVALID = form.dataset.msgInvalid;
|
||||
var MSG_FAILED = form.dataset.msgFailed;
|
||||
var MSG_DEFAULT = form.dataset.msgDefault;
|
||||
var MSG_PENDING = form.dataset.msgPending;
|
||||
var MSG_SIGNING_IN = form.dataset.msgSigningIn;
|
||||
var MSG_SIGN_IN = form.dataset.msgSignIn;
|
||||
|
||||
@@ -174,6 +181,10 @@
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (result.status === 403 && result.data && result.data.error === "registration_pending") {
|
||||
showError(MSG_PENDING);
|
||||
return;
|
||||
}
|
||||
if (result.status === 204 || result.status === 401 || (result.data && !result.data.success)) {
|
||||
showError(MSG_INVALID);
|
||||
return;
|
||||
@@ -200,6 +211,10 @@
|
||||
|
||||
function showForm() {
|
||||
document.getElementById("login-form").hidden = false;
|
||||
var discordEl = document.getElementById("oc-discord-login");
|
||||
if (discordEl) discordEl.hidden = false;
|
||||
var registerEl = document.getElementById("oc-register-link");
|
||||
if (registerEl) registerEl.hidden = false;
|
||||
}
|
||||
|
||||
if ((helloReq.state || helloReq.client_id) && !hasLogin) {
|
||||
|
||||
@@ -336,6 +336,46 @@ main {
|
||||
opacity: 0.92;
|
||||
}
|
||||
|
||||
/* Discord login (Reverse Cloud) */
|
||||
.oc-login-or {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin: 16px 0;
|
||||
color: #fff;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.oc-login-or::before,
|
||||
.oc-login-or::after {
|
||||
content: "";
|
||||
flex: 1;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.4);
|
||||
}
|
||||
|
||||
.oc-login-or span {
|
||||
padding: 0 8px;
|
||||
}
|
||||
|
||||
a.oc-button-discord {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: #5865f2;
|
||||
color: #fff;
|
||||
font-size: 1.0625rem;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
#discord-signup-form div:last-of-type {
|
||||
padding-top: 24px;
|
||||
}
|
||||
|
||||
.oc-hint {
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
font-size: 0.8rem;
|
||||
margin: 6px 0 0;
|
||||
}
|
||||
|
||||
.oc-error-message {
|
||||
color: #fe4600;
|
||||
font-size: 0.875rem;
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
// Package ldapverified wraps the lico LDAP identifier backend so that users
|
||||
// linked to a trusted external identity (Discord) report their email as
|
||||
// verified. The lico LDAP backend always reports email_verified=false.
|
||||
package ldapverified
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/libregraph/lico/identifier/backends"
|
||||
"github.com/libregraph/lico/identity"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// IssuerChecker reports whether an oCIS user has an identity from issuer.
|
||||
type IssuerChecker interface {
|
||||
HasIssuer(ctx context.Context, userID, issuer string) (bool, error)
|
||||
}
|
||||
|
||||
// Backend wraps a lico identifier backend.
|
||||
type Backend struct {
|
||||
backends.Backend
|
||||
Checker IssuerChecker
|
||||
Issuer string
|
||||
Logger logrus.FieldLogger
|
||||
}
|
||||
|
||||
// GetUser implements backends.Backend. Token claims are built from this
|
||||
// lookup, so the email_verified claim follows the wrapped user.
|
||||
func (b *Backend) GetUser(ctx context.Context, userID string, sessionRef *string, requestedScopes map[string]bool) (backends.UserFromBackend, error) {
|
||||
u, err := b.Backend.GetUser(ctx, userID, sessionRef, requestedScopes)
|
||||
if err != nil || u == nil {
|
||||
return u, err
|
||||
}
|
||||
return b.wrap(ctx, u), nil
|
||||
}
|
||||
|
||||
func (b *Backend) wrap(ctx context.Context, u backends.UserFromBackend) backends.UserFromBackend {
|
||||
if _, ok := u.(identity.UserWithEmail); !ok || b.Checker == nil {
|
||||
return u
|
||||
}
|
||||
uid, ok := u.(identity.UserWithUniqueID)
|
||||
if !ok || uid.UniqueID() == "" {
|
||||
return u
|
||||
}
|
||||
linked, err := b.Checker.HasIssuer(ctx, uid.UniqueID(), b.Issuer)
|
||||
if err != nil {
|
||||
if b.Logger != nil {
|
||||
b.Logger.WithError(err).Warnln("could not check linked identity, email stays unverified")
|
||||
}
|
||||
return u
|
||||
}
|
||||
return &user{UserFromBackend: u, linked: linked}
|
||||
}
|
||||
|
||||
// user forwards all optional lico user interfaces of the wrapped user and
|
||||
// overrides EmailVerified.
|
||||
type user struct {
|
||||
backends.UserFromBackend
|
||||
linked bool
|
||||
}
|
||||
|
||||
func (u *user) Email() string {
|
||||
if e, ok := u.UserFromBackend.(identity.UserWithEmail); ok {
|
||||
return e.Email()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (u *user) EmailVerified() bool {
|
||||
if u.linked && u.Email() != "" {
|
||||
return true
|
||||
}
|
||||
if e, ok := u.UserFromBackend.(identity.UserWithEmail); ok {
|
||||
return e.EmailVerified()
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (u *user) Name() string {
|
||||
if p, ok := u.UserFromBackend.(identity.UserWithProfile); ok {
|
||||
return p.Name()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (u *user) FamilyName() string {
|
||||
if p, ok := u.UserFromBackend.(identity.UserWithProfile); ok {
|
||||
return p.FamilyName()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (u *user) GivenName() string {
|
||||
if p, ok := u.UserFromBackend.(identity.UserWithProfile); ok {
|
||||
return p.GivenName()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (u *user) ID() int64 {
|
||||
if i, ok := u.UserFromBackend.(identity.UserWithID); ok {
|
||||
return i.ID()
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (u *user) UniqueID() string {
|
||||
if i, ok := u.UserFromBackend.(identity.UserWithUniqueID); ok {
|
||||
return i.UniqueID()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package ldapverified
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/libregraph/lico/identifier/backends"
|
||||
"github.com/libregraph/lico/identity"
|
||||
)
|
||||
|
||||
type fakeUser struct {
|
||||
sub, mail, uid, name string
|
||||
}
|
||||
|
||||
func (u fakeUser) Subject() string { return u.sub }
|
||||
func (u fakeUser) Username() string { return "alice" }
|
||||
func (u fakeUser) BackendClaims() map[string]interface{} { return nil }
|
||||
func (u fakeUser) BackendScopes() []string { return nil }
|
||||
func (u fakeUser) RequiredScopes() []string { return nil }
|
||||
func (u fakeUser) Email() string { return u.mail }
|
||||
func (u fakeUser) EmailVerified() bool { return false }
|
||||
func (u fakeUser) UniqueID() string { return u.uid }
|
||||
func (u fakeUser) Name() string { return u.name }
|
||||
func (u fakeUser) FamilyName() string { return "" }
|
||||
func (u fakeUser) GivenName() string { return "" }
|
||||
|
||||
type fakeBackend struct {
|
||||
backends.Backend
|
||||
u backends.UserFromBackend
|
||||
}
|
||||
|
||||
func (b fakeBackend) GetUser(context.Context, string, *string, map[string]bool) (backends.UserFromBackend, error) {
|
||||
return b.u, nil
|
||||
}
|
||||
|
||||
func (b fakeBackend) Name() string { return "identifier-ldap" }
|
||||
|
||||
type fakeChecker struct {
|
||||
linked map[string]bool
|
||||
err error
|
||||
issuer string
|
||||
}
|
||||
|
||||
func (c *fakeChecker) HasIssuer(_ context.Context, userID, issuer string) (bool, error) {
|
||||
c.issuer = issuer
|
||||
return c.linked[userID], c.err
|
||||
}
|
||||
|
||||
func get(t *testing.T, b *Backend) identity.UserWithEmail {
|
||||
t.Helper()
|
||||
u, err := b.GetUser(context.Background(), "entry", nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
e, ok := u.(identity.UserWithEmail)
|
||||
if !ok {
|
||||
t.Fatal("wrapped user lost the email interface")
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
func TestLinkedUserEmailIsVerified(t *testing.T) {
|
||||
c := &fakeChecker{linked: map[string]bool{"uuid-1": true}}
|
||||
b := &Backend{Backend: fakeBackend{u: fakeUser{sub: "s", mail: "a@example.com", uid: "uuid-1", name: "Alice"}}, Checker: c, Issuer: "https://discord.com"}
|
||||
u := get(t, b)
|
||||
if !u.EmailVerified() || u.Email() != "a@example.com" || c.issuer != "https://discord.com" {
|
||||
t.Errorf("verified = %v email = %q issuer = %q", u.EmailVerified(), u.Email(), c.issuer)
|
||||
}
|
||||
if p, ok := u.(identity.UserWithProfile); !ok || p.Name() != "Alice" {
|
||||
t.Error("profile not forwarded")
|
||||
}
|
||||
if id, ok := u.(identity.UserWithUniqueID); !ok || id.UniqueID() != "uuid-1" {
|
||||
t.Error("unique id not forwarded")
|
||||
}
|
||||
if b.Name() != "identifier-ldap" {
|
||||
t.Error("backend name must stay the same so existing logon cookies stay valid")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnlinkedOrFailingUserStaysUnverified(t *testing.T) {
|
||||
for name, c := range map[string]*fakeChecker{
|
||||
"not linked": {linked: map[string]bool{}},
|
||||
"lookup error": {linked: map[string]bool{"uuid-1": true}, err: errors.New("ldap down")},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
b := &Backend{Backend: fakeBackend{u: fakeUser{mail: "a@example.com", uid: "uuid-1"}}, Checker: c}
|
||||
if get(t, b).EmailVerified() {
|
||||
t.Error("email must not be verified")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLinkedUserWithoutEmailIsNotVerified(t *testing.T) {
|
||||
c := &fakeChecker{linked: map[string]bool{"uuid-1": true}}
|
||||
b := &Backend{Backend: fakeBackend{u: fakeUser{uid: "uuid-1"}}, Checker: c}
|
||||
if get(t, b).EmailVerified() {
|
||||
t.Error("an empty email must not be verified")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package ldapverified
|
||||
|
||||
import (
|
||||
"crypto/x509"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/libregraph/lico/bootstrap"
|
||||
"github.com/libregraph/lico/identifier"
|
||||
licoldap "github.com/libregraph/lico/identifier/backends/ldap"
|
||||
"github.com/libregraph/lico/identity"
|
||||
"github.com/libregraph/lico/identity/managers"
|
||||
)
|
||||
|
||||
const identityManagerName = "ldap"
|
||||
|
||||
// Register registers the "ldap" identity manager. It is the lico LDAP
|
||||
// identity manager (bootstrap/backends/ldap) with the identifier backend
|
||||
// wrapped by Backend. It replaces the lico registration of the same name.
|
||||
func Register(checker IssuerChecker, issuer string) error {
|
||||
return bootstrap.RegisterIdentityManager(identityManagerName, func(bs bootstrap.Bootstrap) (identity.Manager, error) {
|
||||
return newIdentityManager(bs, checker, issuer)
|
||||
})
|
||||
}
|
||||
|
||||
// newIdentityManager mirrors bsldap.NewIdentityManager of lico v0.68.0.
|
||||
func newIdentityManager(bs bootstrap.Bootstrap, checker IssuerChecker, issuer string) (identity.Manager, error) {
|
||||
config := bs.Config()
|
||||
logger := config.Config.Logger
|
||||
|
||||
if config.AuthorizationEndpointURI.String() != "" {
|
||||
return nil, fmt.Errorf("ldap backend is incompatible with authorization-endpoint-uri parameter")
|
||||
}
|
||||
config.AuthorizationEndpointURI.Path = bs.MakeURIPath(bootstrap.APITypeSignin, "/identifier/_/authorize")
|
||||
|
||||
if config.EndSessionEndpointURI.String() != "" {
|
||||
return nil, fmt.Errorf("ldap backend is incompatible with endsession-endpoint-uri parameter")
|
||||
}
|
||||
config.EndSessionEndpointURI.Path = bs.MakeURIPath(bootstrap.APITypeSignin, "/identifier/_/endsession")
|
||||
|
||||
if config.SignInFormURI.EscapedPath() == "" {
|
||||
config.SignInFormURI.Path = bs.MakeURIPath(bootstrap.APITypeSignin, "/identifier")
|
||||
}
|
||||
if config.SignedOutURI.EscapedPath() == "" {
|
||||
config.SignedOutURI.Path = bs.MakeURIPath(bootstrap.APITypeSignin, "/goodbye")
|
||||
}
|
||||
|
||||
attributeMapping := map[string]string{
|
||||
licoldap.AttributeLogin: os.Getenv("LDAP_LOGIN_ATTRIBUTE"),
|
||||
licoldap.AttributeEmail: os.Getenv("LDAP_EMAIL_ATTRIBUTE"),
|
||||
licoldap.AttributeName: os.Getenv("LDAP_NAME_ATTRIBUTE"),
|
||||
licoldap.AttributeFamilyName: os.Getenv("LDAP_FAMILY_NAME_ATTRIBUTE"),
|
||||
licoldap.AttributeGivenName: os.Getenv("LDAP_GIVEN_NAME_ATTRIBUTE"),
|
||||
licoldap.AttributeUUID: os.Getenv("LDAP_UUID_ATTRIBUTE"),
|
||||
fmt.Sprintf("%s_type", licoldap.AttributeUUID): os.Getenv("LDAP_UUID_ATTRIBUTE_TYPE"),
|
||||
}
|
||||
if numericUIDAttribute := os.Getenv("LDAP_UIDNUMBER_ATTRIBUTE"); numericUIDAttribute != "" {
|
||||
attributeMapping[licoldap.AttributeNumericUID] = numericUIDAttribute
|
||||
}
|
||||
var subMapping []string
|
||||
if s := os.Getenv("LDAP_SUB_ATTRIBUTES"); s != "" {
|
||||
subMapping = strings.Split(s, " ")
|
||||
}
|
||||
|
||||
tlsConfig := config.TLSClientConfig.Clone()
|
||||
if caCertFile := os.Getenv("LDAP_TLS_CACERT"); caCertFile != "" {
|
||||
pemBytes, err := os.ReadFile(caCertFile)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read CA certificate(s) from '%s': %w", caCertFile, err)
|
||||
}
|
||||
rpool, _ := x509.SystemCertPool()
|
||||
if rpool == nil {
|
||||
rpool = x509.NewCertPool()
|
||||
}
|
||||
if !rpool.AppendCertsFromPEM(pemBytes) {
|
||||
return nil, fmt.Errorf("failed to append CA certificate(s) from '%s' to pool", caCertFile)
|
||||
}
|
||||
tlsConfig.RootCAs = rpool
|
||||
}
|
||||
|
||||
ldapBackend, err := licoldap.NewLDAPIdentifierBackend(
|
||||
config.Config,
|
||||
tlsConfig,
|
||||
os.Getenv("LDAP_URI"),
|
||||
os.Getenv("LDAP_BINDDN"),
|
||||
os.Getenv("LDAP_BINDPW"),
|
||||
os.Getenv("LDAP_BASEDN"),
|
||||
os.Getenv("LDAP_SCOPE"),
|
||||
os.Getenv("LDAP_FILTER"),
|
||||
subMapping,
|
||||
attributeMapping,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create identifier backend: %v", err)
|
||||
}
|
||||
wrapped := &Backend{Backend: ldapBackend, Checker: checker, Issuer: issuer, Logger: logger}
|
||||
|
||||
fullAuthorizationEndpointURL := bootstrap.WithSchemeAndHost(config.AuthorizationEndpointURI, config.IssuerIdentifierURI)
|
||||
fullSignInFormURL := bootstrap.WithSchemeAndHost(config.SignInFormURI, config.IssuerIdentifierURI)
|
||||
fullSignedOutEndpointURL := bootstrap.WithSchemeAndHost(config.SignedOutURI, config.IssuerIdentifierURI)
|
||||
|
||||
activeIdentifier, err := identifier.NewIdentifier(&identifier.Config{
|
||||
Config: config.Config,
|
||||
|
||||
BaseURI: config.IssuerIdentifierURI,
|
||||
PathPrefix: bs.MakeURIPath(bootstrap.APITypeSignin, ""),
|
||||
StaticFolder: config.IdentifierClientPath,
|
||||
ScopesConf: config.IdentifierScopesConf,
|
||||
WebAppDisabled: config.IdentifierClientDisabled,
|
||||
|
||||
LogonCookieName: "__Secure-KKT", // Kopano-Konnect-Token
|
||||
LogonCookieSameSite: config.CookieSameSite,
|
||||
|
||||
ConsentCookieSameSite: config.CookieSameSite,
|
||||
StateCookieSameSite: config.CookieSameSite,
|
||||
|
||||
AuthorizationEndpointURI: fullAuthorizationEndpointURL,
|
||||
SignedOutEndpointURI: fullSignedOutEndpointURL,
|
||||
|
||||
DefaultBannerLogo: config.IdentifierDefaultBannerLogo,
|
||||
DefaultBannerLogoHeight: config.IdentifierDefaultBannerLogoHeight,
|
||||
DefaultSignInPageText: config.IdentifierDefaultSignInPageText,
|
||||
DefaultSignInPageLogoURI: config.IdentifierDefaultLogoTargetURI,
|
||||
DefaultUsernameHintText: config.IdentifierDefaultUsernameHintText,
|
||||
UILocales: config.IdentifierUILocales,
|
||||
|
||||
Backend: wrapped,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create identifier: %v", err)
|
||||
}
|
||||
if err := activeIdentifier.SetKey(config.EncryptionSecret); err != nil {
|
||||
return nil, fmt.Errorf("invalid --encryption-secret parameter value for identifier: %v", err)
|
||||
}
|
||||
|
||||
bs.Managers().Set("identifier", activeIdentifier)
|
||||
|
||||
identityManagerConfig := &identity.Config{
|
||||
SignInFormURI: fullSignInFormURL,
|
||||
SignedOutURI: fullSignedOutEndpointURL,
|
||||
|
||||
Logger: logger,
|
||||
|
||||
ScopesSupported: config.Config.AllowedScopes,
|
||||
AllowSignedLogin: config.Config.AllowClientSignedLogins,
|
||||
}
|
||||
|
||||
im := managers.NewIdentifierIdentityManager(identityManagerConfig, activeIdentifier)
|
||||
logger.Infoln("using identifier backed identity manager (ldap, verified external identities)")
|
||||
return im, nil
|
||||
}
|
||||
@@ -23,6 +23,10 @@ type Config struct {
|
||||
|
||||
MachineAuthAPIKey string `yaml:"machine_auth_api_key" env:"OCIS_MACHINE_AUTH_API_KEY;IDP_MACHINE_AUTH_API_KEY" desc:"Machine auth API key used to validate internal requests necessary for the access to resources from other services." introductionVersion:"pre5.0"`
|
||||
|
||||
TokenManager *TokenManager `yaml:"token_manager"`
|
||||
ServiceAccount ServiceAccount `yaml:"service_account" mask:"struct"`
|
||||
Discord Discord `yaml:"discord"`
|
||||
|
||||
Asset Asset `yaml:"asset"`
|
||||
IDP Settings `yaml:"idp"`
|
||||
Clients []Client `yaml:"clients"`
|
||||
@@ -31,6 +35,23 @@ type Config struct {
|
||||
Context context.Context `yaml:"-"`
|
||||
}
|
||||
|
||||
// TokenManager is the config for using the reva token manager.
|
||||
type TokenManager struct {
|
||||
JWTSecret string `yaml:"jwt_secret" env:"OCIS_JWT_SECRET;IDP_JWT_SECRET" desc:"The secret to validate reva access tokens. Used by the Discord login admin API." introductionVersion:"8.3.0" mask:"password"`
|
||||
}
|
||||
|
||||
// ServiceAccount is the configuration for the used service account.
|
||||
type ServiceAccount struct {
|
||||
ServiceAccountID string `yaml:"service_account_id" env:"OCIS_SERVICE_ACCOUNT_ID;IDP_SERVICE_ACCOUNT_ID" desc:"The ID of the service account the service should use. Required to provision Discord users. See the 'auth-service' service description for more details." introductionVersion:"8.3.0"`
|
||||
ServiceAccountSecret string `yaml:"service_account_secret" env:"OCIS_SERVICE_ACCOUNT_SECRET;IDP_SERVICE_ACCOUNT_SECRET" desc:"The service account secret." introductionVersion:"8.3.0" mask:"password"`
|
||||
}
|
||||
|
||||
// Discord configures the Discord OAuth2 login. The client credentials and
|
||||
// the allowed guild are managed in the Admin Settings UI.
|
||||
type Discord struct {
|
||||
SettingsFile string `yaml:"settings_file" env:"IDP_DISCORD_SETTINGS_FILE" desc:"Path of the file that stores the Discord login settings managed in the Admin Settings UI. If not defined, the root directory derives from $OCIS_BASE_DATA_PATH/idp." introductionVersion:"8.3.0"`
|
||||
}
|
||||
|
||||
// Ldap defines the available LDAP configuration.
|
||||
type Ldap struct {
|
||||
URI string `yaml:"uri" env:"OCIS_LDAP_URI;IDP_LDAP_URI" desc:"Url of the LDAP service to use as IDP." introductionVersion:"pre5.0"`
|
||||
|
||||
@@ -37,6 +37,9 @@ func DefaultConfig() *config.Config {
|
||||
Service: config.Service{
|
||||
Name: "idp",
|
||||
},
|
||||
Discord: config.Discord{
|
||||
SettingsFile: filepath.Join(defaults.BaseDataPath(), "idp", "discord.json"),
|
||||
},
|
||||
IDP: config.Settings{
|
||||
Iss: "https://localhost:9200",
|
||||
IdentityManager: "ldap",
|
||||
@@ -164,6 +167,14 @@ func EnsureDefaults(cfg *config.Config) {
|
||||
if cfg.MachineAuthAPIKey == "" && cfg.Commons != nil && cfg.Commons.MachineAuthAPIKey != "" {
|
||||
cfg.MachineAuthAPIKey = cfg.Commons.MachineAuthAPIKey
|
||||
}
|
||||
|
||||
if cfg.TokenManager == nil && cfg.Commons != nil && cfg.Commons.TokenManager != nil {
|
||||
cfg.TokenManager = &config.TokenManager{
|
||||
JWTSecret: cfg.Commons.TokenManager.JWTSecret,
|
||||
}
|
||||
} else if cfg.TokenManager == nil {
|
||||
cfg.TokenManager = &config.TokenManager{}
|
||||
}
|
||||
}
|
||||
|
||||
// Sanitize sanitizes the configuration
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
|
||||
userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
permissionsapi "github.com/cs3org/go-cs3apis/cs3/permissions/v1beta1"
|
||||
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
|
||||
"github.com/owncloud/reva/v2/pkg/auth/scope"
|
||||
revactx "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
|
||||
"github.com/owncloud/reva/v2/pkg/token"
|
||||
"github.com/owncloud/reva/v2/pkg/token/manager/jwt"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
// SettingsPermission is the permission required to manage Discord login.
|
||||
const SettingsPermission = "Settings.ReadWrite"
|
||||
|
||||
var (
|
||||
errUnauthenticated = errors.New("unauthenticated")
|
||||
errForbidden = errors.New("forbidden")
|
||||
)
|
||||
|
||||
// PermissionChecker checks a named permission for a user ID.
|
||||
type PermissionChecker interface {
|
||||
HasPermission(r *http.Request, token, userID, permission string) (bool, error)
|
||||
}
|
||||
|
||||
// GatewayPermissionChecker asks the CS3 gateway (settings service).
|
||||
type GatewayPermissionChecker struct {
|
||||
Selector pool.Selectable[gateway.GatewayAPIClient]
|
||||
}
|
||||
|
||||
// HasPermission implements PermissionChecker.
|
||||
func (g GatewayPermissionChecker) HasPermission(r *http.Request, tkn, userID, permission string) (bool, error) {
|
||||
client, err := g.Selector.Next()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
ctx := metadata.AppendToOutgoingContext(r.Context(), revactx.TokenHeader, tkn)
|
||||
rsp, err := client.CheckPermission(ctx, &permissionsapi.CheckPermissionRequest{
|
||||
Permission: permission,
|
||||
SubjectRef: &permissionsapi.SubjectReference{
|
||||
Spec: &permissionsapi.SubjectReference_UserId{
|
||||
UserId: &userv1beta1.UserId{OpaqueId: userID},
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return rsp.GetStatus().GetCode() == rpc.Code_CODE_OK, nil
|
||||
}
|
||||
|
||||
// JWTAdminAuthorizer verifies the reva access token the proxy puts into the
|
||||
// x-access-token header and checks the Settings.ReadWrite permission.
|
||||
type JWTAdminAuthorizer struct {
|
||||
Tokens token.Manager
|
||||
Permissions PermissionChecker
|
||||
}
|
||||
|
||||
// NewJWTAdminAuthorizer returns an authorizer for the given JWT secret.
|
||||
func NewJWTAdminAuthorizer(secret string, perms PermissionChecker) (*JWTAdminAuthorizer, error) {
|
||||
if secret == "" {
|
||||
return nil, errors.New("jwt secret is required")
|
||||
}
|
||||
tm, err := jwt.New(map[string]interface{}{"secret": secret, "expires": int64(24 * 60 * 60)})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &JWTAdminAuthorizer{Tokens: tm, Permissions: perms}, nil
|
||||
}
|
||||
|
||||
// AuthenticateUser implements UserAuthenticator.
|
||||
func (a *JWTAdminAuthorizer) AuthenticateUser(r *http.Request) (string, int, error) {
|
||||
tkn := r.Header.Get(revactx.TokenHeader)
|
||||
if tkn == "" {
|
||||
return "", http.StatusUnauthorized, errUnauthenticated
|
||||
}
|
||||
u, tokenScope, err := a.Tokens.DismantleToken(r.Context(), tkn)
|
||||
if err != nil || u.GetId().GetOpaqueId() == "" {
|
||||
return "", http.StatusUnauthorized, errUnauthenticated
|
||||
}
|
||||
if ok, err := scope.VerifyScope(r.Context(), tokenScope, r); err != nil || !ok {
|
||||
return "", http.StatusUnauthorized, errUnauthenticated
|
||||
}
|
||||
return u.GetId().GetOpaqueId(), http.StatusOK, nil
|
||||
}
|
||||
|
||||
// AuthorizeAdmin implements AdminAuthorizer.
|
||||
func (a *JWTAdminAuthorizer) AuthorizeAdmin(r *http.Request) (int, error) {
|
||||
userID, status, err := a.AuthenticateUser(r)
|
||||
if err != nil {
|
||||
return status, err
|
||||
}
|
||||
ok, err := a.Permissions.HasPermission(r, r.Header.Get(revactx.TokenHeader), userID, SettingsPermission)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
if !ok {
|
||||
return http.StatusForbidden, errForbidden
|
||||
}
|
||||
return http.StatusOK, nil
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
authpb "github.com/cs3org/go-cs3apis/cs3/auth/provider/v1beta1"
|
||||
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
"github.com/owncloud/reva/v2/pkg/auth/scope"
|
||||
revactx "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
)
|
||||
|
||||
const testJWTSecret = "test-jwt-secret"
|
||||
|
||||
type fakePerms struct {
|
||||
ok bool
|
||||
err error
|
||||
gotUser string
|
||||
gotPerm string
|
||||
gotToken string
|
||||
}
|
||||
|
||||
func (f *fakePerms) HasPermission(_ *http.Request, tkn, userID, perm string) (bool, error) {
|
||||
f.gotToken, f.gotUser, f.gotPerm = tkn, userID, perm
|
||||
return f.ok, f.err
|
||||
}
|
||||
|
||||
func mintTestToken(t *testing.T, secret, userID string) string {
|
||||
t.Helper()
|
||||
a, err := NewJWTAdminAuthorizer(secret, &fakePerms{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := scope.AddOwnerScope(map[string]*authpb.Scope{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tok, err := a.Tokens.MintToken(context.Background(), &userpb.User{
|
||||
Id: &userpb.UserId{OpaqueId: userID, Idp: "https://cloud.example.com"},
|
||||
Username: "admin",
|
||||
}, s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return tok
|
||||
}
|
||||
|
||||
func adminRequest(token string) *http.Request {
|
||||
r := httptest.NewRequest(http.MethodGet, "/oauth2/discord/admin/settings", nil)
|
||||
if token != "" {
|
||||
r.Header.Set(revactx.TokenHeader, token)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func TestJWTAdminAuthorizer(t *testing.T) {
|
||||
adminToken := mintTestToken(t, testJWTSecret, "admin-id")
|
||||
foreignToken := mintTestToken(t, "another-secret", "admin-id")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
token string
|
||||
perms *fakePerms
|
||||
wantStatus int
|
||||
}{
|
||||
{"no token", "", &fakePerms{ok: true}, http.StatusUnauthorized},
|
||||
{"garbage token", "not-a-jwt", &fakePerms{ok: true}, http.StatusUnauthorized},
|
||||
{"token signed with another secret", foreignToken, &fakePerms{ok: true}, http.StatusUnauthorized},
|
||||
{"missing permission", adminToken, &fakePerms{ok: false}, http.StatusForbidden},
|
||||
{"permission check fails", adminToken, &fakePerms{err: errors.New("gateway down")}, http.StatusInternalServerError},
|
||||
{"admin", adminToken, &fakePerms{ok: true}, http.StatusOK},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
a, err := NewJWTAdminAuthorizer(testJWTSecret, tt.perms)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
status, err := a.AuthorizeAdmin(adminRequest(tt.token))
|
||||
if status != tt.wantStatus {
|
||||
t.Fatalf("status = %d, want %d (err %v)", status, tt.wantStatus, err)
|
||||
}
|
||||
if (status == http.StatusOK) != (err == nil) {
|
||||
t.Errorf("status %d with err %v", status, err)
|
||||
}
|
||||
if tt.wantStatus == http.StatusOK || tt.wantStatus == http.StatusForbidden {
|
||||
if tt.perms.gotUser != "admin-id" || tt.perms.gotPerm != SettingsPermission || tt.perms.gotToken != adminToken {
|
||||
t.Errorf("permission checked for %q/%q", tt.perms.gotUser, tt.perms.gotPerm)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewJWTAdminAuthorizerRequiresSecret(t *testing.T) {
|
||||
if _, err := NewJWTAdminAuthorizer("", &fakePerms{}); err == nil {
|
||||
t.Error("expected an error without a jwt secret")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
// Accounts enables or deletes accounts waiting for approval.
|
||||
type Accounts interface {
|
||||
Approve(ctx context.Context, userID string) error
|
||||
Reject(ctx context.Context, userID string) error
|
||||
}
|
||||
|
||||
// listPending serves GET /oauth2/discord/admin/pending.
|
||||
func (h *Handler) listPending(w http.ResponseWriter, r *http.Request) {
|
||||
if status, err := h.opt.Admin.AuthorizeAdmin(r); err != nil {
|
||||
writeJSONError(w, status, "accessDenied", "", http.StatusText(status))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"value": h.opt.Pending.List()})
|
||||
}
|
||||
|
||||
// approvePending serves POST /oauth2/discord/admin/pending/{id}/approve.
|
||||
func (h *Handler) approvePending(w http.ResponseWriter, r *http.Request) {
|
||||
h.decidePending(w, r, true)
|
||||
}
|
||||
|
||||
// rejectPending serves POST /oauth2/discord/admin/pending/{id}/reject.
|
||||
func (h *Handler) rejectPending(w http.ResponseWriter, r *http.Request) {
|
||||
h.decidePending(w, r, false)
|
||||
}
|
||||
|
||||
func (h *Handler) decidePending(w http.ResponseWriter, r *http.Request, approve bool) {
|
||||
if status, err := h.opt.Admin.AuthorizeAdmin(r); err != nil {
|
||||
writeJSONError(w, status, "accessDenied", "", http.StatusText(status))
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "id")
|
||||
if _, ok := h.opt.Pending.Get(id); !ok {
|
||||
writeJSONError(w, http.StatusNotFound, "itemNotFound", "", "no pending account with this id")
|
||||
return
|
||||
}
|
||||
logger := h.opt.Logger.With().Str("component", "discord").Str("user_id", id).Logger()
|
||||
var err error
|
||||
if approve {
|
||||
err = h.opt.Accounts.Approve(r.Context(), id)
|
||||
} else {
|
||||
err = h.opt.Accounts.Reject(r.Context(), id)
|
||||
}
|
||||
if err != nil {
|
||||
logger.Error().Err(err).Bool("approve", approve).Msg("could not decide pending account")
|
||||
writeJSONError(w, http.StatusBadGateway, "generalException", "", "could not update the account")
|
||||
return
|
||||
}
|
||||
// Only forget the entry after the directory change succeeded, so a
|
||||
// failed approval can be retried.
|
||||
if err := h.opt.Pending.Remove(id); err != nil {
|
||||
logger.Error().Err(err).Msg("could not remove pending entry")
|
||||
writeJSONError(w, http.StatusInternalServerError, "generalException", "", "could not save pending accounts")
|
||||
return
|
||||
}
|
||||
logger.Info().Bool("approve", approve).Msg("pending account decided")
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type fakeAccounts struct {
|
||||
approved, rejected []string
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeAccounts) Approve(_ context.Context, id string) error {
|
||||
if f.err != nil {
|
||||
return f.err
|
||||
}
|
||||
f.approved = append(f.approved, id)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeAccounts) Reject(_ context.Context, id string) error {
|
||||
if f.err != nil {
|
||||
return f.err
|
||||
}
|
||||
f.rejected = append(f.rejected, id)
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestAdminListPending(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
_ = h.pending.Add(PendingUser{UserID: "u1", Username: "alice", Source: SourceWeb})
|
||||
rec := h.do(http.MethodGet, "/oauth2/discord/admin/pending", nil)
|
||||
var body struct{ Value []PendingUser }
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil || rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d body = %s", rec.Code, rec.Body)
|
||||
}
|
||||
if len(body.Value) != 1 || body.Value[0].Source != SourceWeb {
|
||||
t.Fatalf("value = %+v", body.Value)
|
||||
}
|
||||
h.admin.status = http.StatusForbidden
|
||||
if rec := h.do(http.MethodGet, "/oauth2/discord/admin/pending", nil); rec.Code != http.StatusForbidden {
|
||||
t.Errorf("without permission = %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminApproveThenDiscordLoginSucceeds(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
if err := h.reg.Save(RegistrationSettings{AllowRegistration: true, AllowDiscord: true, RequireApproval: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f, ck := h.startSignup("")
|
||||
h.postSignup(url.Values{"token": {f.Token}, "username": {"alice2"}}, ck)
|
||||
if !h.pending.IsPending(h.prov.id) {
|
||||
t.Fatal("account must be pending")
|
||||
}
|
||||
|
||||
rec := h.do(http.MethodPost, "/oauth2/discord/admin/pending/"+h.prov.id+"/approve", nil)
|
||||
if rec.Code != http.StatusNoContent || len(h.accounts.approved) != 1 || h.pending.IsPending(h.prov.id) {
|
||||
t.Fatalf("approve status = %d approved = %v", rec.Code, h.accounts.approved)
|
||||
}
|
||||
|
||||
h.sess.userID = ""
|
||||
state, c := h.login("")
|
||||
if rec := h.callback(cbQuery(testCode, state), c); rec.Code != http.StatusOK || h.sess.userID != h.prov.id {
|
||||
t.Fatalf("login after approval: status = %d logon = %q", rec.Code, h.sess.userID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminRejectAndErrors(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
_ = h.pending.Add(PendingUser{UserID: "u1", Username: "alice", Source: SourceWeb})
|
||||
|
||||
if rec := h.do(http.MethodPost, "/oauth2/discord/admin/pending/unknown/reject", nil); rec.Code != http.StatusNotFound {
|
||||
t.Errorf("unknown id = %d", rec.Code)
|
||||
}
|
||||
|
||||
h.accounts.err = errors.New("graph down")
|
||||
if rec := h.do(http.MethodPost, "/oauth2/discord/admin/pending/u1/reject", nil); rec.Code != http.StatusBadGateway || !h.pending.IsPending("u1") {
|
||||
t.Fatalf("failed reject = %d, entry must stay", rec.Code)
|
||||
}
|
||||
|
||||
h.accounts.err = nil
|
||||
if rec := h.do(http.MethodPost, "/oauth2/discord/admin/pending/u1/reject", nil); rec.Code != http.StatusNoContent || h.pending.IsPending("u1") || len(h.accounts.rejected) != 1 {
|
||||
t.Fatalf("reject = %d rejected = %v", rec.Code, h.accounts.rejected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGraphProvisionerApproveReject(t *testing.T) {
|
||||
dir := newFakeDirectory()
|
||||
p := GraphProvisioner{Dir: dir, Index: fakeIndex{}}
|
||||
if err := p.Approve(context.Background(), "u1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if e := dir.updates["u1"].AccountEnabled; e == nil || !*e {
|
||||
t.Fatalf("approve patch = %+v", dir.updates["u1"])
|
||||
}
|
||||
if err := p.Reject(context.Background(), "u2"); err != nil || len(dir.deleted) != 1 || dir.deleted[0] != "u2" {
|
||||
t.Fatalf("reject: err = %v deleted = %v", err, dir.deleted)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDiscordOnlySignupWithApprovalCreatesPendingAccount(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
if err := h.reg.Save(RegistrationSettings{AllowRegistration: true, AllowWeb: false, AllowDiscord: true, RequireApproval: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f, ck := h.startSignup("client_id=web")
|
||||
rec := h.postSignup(url.Values{"token": {f.Token}, "username": {"alice2"}}, ck)
|
||||
if rec.Code != http.StatusOK || h.render.code != ErrCodeRegistrationSubmitted {
|
||||
t.Fatalf("status = %d code = %q", rec.Code, h.render.code)
|
||||
}
|
||||
if len(h.prov.createdEnabled) != 1 || h.prov.createdEnabled[0] {
|
||||
t.Fatalf("account must be created disabled, got %v", h.prov.createdEnabled)
|
||||
}
|
||||
if h.sess.userID != "" {
|
||||
t.Error("no logon may be issued for a pending account")
|
||||
}
|
||||
p, ok := h.pending.Get(h.prov.id)
|
||||
if !ok || p.Source != SourceDiscord || p.Username != "alice2" || p.RequestedAt.IsZero() {
|
||||
t.Fatalf("pending = %+v ok = %v", p, ok)
|
||||
}
|
||||
if c := findCookie(rec, signupCookieName); c == nil || c.MaxAge >= 0 {
|
||||
t.Error("signup cookie was not cleared")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignupWithoutApprovalCreatesEnabledAccount(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
f, ck := h.startSignup("")
|
||||
h.postSignup(url.Values{"token": {f.Token}, "username": {"alice2"}}, ck)
|
||||
if len(h.prov.createdEnabled) != 1 || !h.prov.createdEnabled[0] {
|
||||
t.Fatalf("createdEnabled = %v", h.prov.createdEnabled)
|
||||
}
|
||||
if h.pending.IsPending(h.prov.id) || h.sess.userID != h.prov.id {
|
||||
t.Error("account without approval must log on directly")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscordRegistrationClosed(t *testing.T) {
|
||||
for name, s := range map[string]RegistrationSettings{
|
||||
"discord off": {AllowRegistration: true, AllowWeb: true},
|
||||
"registration off": {AllowDiscord: true},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
if err := h.reg.Save(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.prov.missing = true
|
||||
state, c := h.login("")
|
||||
rec := h.callback(cbQuery(testCode, state), c)
|
||||
if rec.Code != http.StatusForbidden || h.render.code != ErrCodeRegistrationClosed {
|
||||
t.Fatalf("status = %d code = %q", rec.Code, h.render.code)
|
||||
}
|
||||
if h.render.signup != nil || len(h.prov.created) != 0 {
|
||||
t.Error("signup form shown or account created while closed")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignupClosedAfterFormWasShown(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
f, ck := h.startSignup("")
|
||||
if err := h.reg.Save(RegistrationSettings{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := h.postSignup(url.Values{"token": {f.Token}, "username": {"alice2"}}, ck)
|
||||
if rec.Code != http.StatusForbidden || len(h.prov.created) != 0 {
|
||||
t.Fatalf("status = %d created = %v", rec.Code, h.prov.created)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPendingUserCannotLogInWithDiscord(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
if err := h.pending.Add(PendingUser{UserID: h.prov.id, Username: "alice", Source: SourceDiscord}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state, c := h.login("")
|
||||
rec := h.callback(cbQuery(testCode, state), c)
|
||||
if rec.Code != http.StatusForbidden || h.render.code != ErrCodePendingApproval {
|
||||
t.Fatalf("status = %d code = %q", rec.Code, h.render.code)
|
||||
}
|
||||
if h.sess.userID != "" {
|
||||
t.Error("logon issued for a pending account")
|
||||
}
|
||||
|
||||
// After approval the same login succeeds.
|
||||
if err := h.pending.Remove(h.prov.id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state, c = h.login("")
|
||||
if rec := h.callback(cbQuery(testCode, state), c); rec.Code != http.StatusOK || h.sess.userID != h.prov.id {
|
||||
t.Fatalf("status = %d logon = %q", rec.Code, h.sess.userID)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultAPIBase is the Discord REST API base URL.
|
||||
DefaultAPIBase = "https://discord.com/api/v10"
|
||||
// DefaultAuthorizeURL is the Discord OAuth2 authorization endpoint.
|
||||
DefaultAuthorizeURL = "https://discord.com/oauth2/authorize"
|
||||
// OAuthScopes are the scopes requested from Discord.
|
||||
OAuthScopes = "identify email guilds"
|
||||
|
||||
maxBodyBytes = 1 << 20
|
||||
guildPageSize = 200
|
||||
maxGuildPages = 10
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrInvalidGrant means Discord rejected the authorization code.
|
||||
ErrInvalidGrant = errors.New("discord rejected the authorization code")
|
||||
// ErrInvalidClient means Discord rejected the client ID or secret.
|
||||
ErrInvalidClient = errors.New("discord rejected the client credentials")
|
||||
// ErrUpstream means a Discord API request failed for another reason.
|
||||
ErrUpstream = errors.New("discord api request failed")
|
||||
)
|
||||
|
||||
// User is the subset of GET /users/@me used for provisioning.
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
GlobalName string `json:"global_name"`
|
||||
Email string `json:"email"`
|
||||
Verified bool `json:"verified"`
|
||||
}
|
||||
|
||||
// DisplayName returns the global display name, falling back to the username.
|
||||
func (u *User) DisplayName() string {
|
||||
if g := strings.TrimSpace(u.GlobalName); g != "" {
|
||||
return g
|
||||
}
|
||||
return u.Username
|
||||
}
|
||||
|
||||
// VerifiedEmail returns the email only when Discord marks it as verified.
|
||||
func (u *User) VerifiedEmail() string {
|
||||
if u.Verified {
|
||||
return strings.TrimSpace(u.Email)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Guild is the subset of a GET /users/@me/guilds entry.
|
||||
type Guild struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// Client talks to the Discord OAuth2 and REST API.
|
||||
type Client struct {
|
||||
HTTP *http.Client
|
||||
APIBase string
|
||||
AuthorizeURL string
|
||||
}
|
||||
|
||||
// NewClient returns a client for the public Discord API.
|
||||
func NewClient() *Client {
|
||||
return &Client{
|
||||
HTTP: &http.Client{Timeout: 10 * time.Second},
|
||||
APIBase: DefaultAPIBase,
|
||||
AuthorizeURL: DefaultAuthorizeURL,
|
||||
}
|
||||
}
|
||||
|
||||
// AuthCodeURL builds the URL the browser is sent to for authorization.
|
||||
func (c *Client) AuthCodeURL(clientID, redirectURI, state string) string {
|
||||
v := url.Values{}
|
||||
v.Set("response_type", "code")
|
||||
v.Set("client_id", clientID)
|
||||
v.Set("redirect_uri", redirectURI)
|
||||
v.Set("scope", OAuthScopes)
|
||||
v.Set("state", state)
|
||||
// Skip the consent screen when the user already authorized the app.
|
||||
v.Set("prompt", "none")
|
||||
return c.AuthorizeURL + "?" + v.Encode()
|
||||
}
|
||||
|
||||
// Exchange trades the authorization code for an access token.
|
||||
func (c *Client) Exchange(ctx context.Context, clientID, clientSecret, code, redirectURI string) (string, error) {
|
||||
form := url.Values{
|
||||
"grant_type": {"authorization_code"},
|
||||
"code": {code},
|
||||
"redirect_uri": {redirectURI},
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.APIBase+"/oauth2/token", strings.NewReader(form.Encode()))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.SetBasicAuth(url.QueryEscape(clientID), url.QueryEscape(clientSecret))
|
||||
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%w: %v", ErrUpstream, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, maxBodyBytes))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%w: %v", ErrUpstream, err)
|
||||
}
|
||||
|
||||
switch resp.StatusCode {
|
||||
case http.StatusOK:
|
||||
case http.StatusBadRequest:
|
||||
return "", ErrInvalidGrant
|
||||
case http.StatusUnauthorized:
|
||||
return "", ErrInvalidClient
|
||||
default:
|
||||
return "", fmt.Errorf("%w: token endpoint returned %d", ErrUpstream, resp.StatusCode)
|
||||
}
|
||||
|
||||
var tok struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &tok); err != nil || tok.AccessToken == "" {
|
||||
return "", fmt.Errorf("%w: token response without access_token", ErrUpstream)
|
||||
}
|
||||
return tok.AccessToken, nil
|
||||
}
|
||||
|
||||
// GetUser returns the authorized user (GET /users/@me).
|
||||
func (c *Client) GetUser(ctx context.Context, token string) (*User, error) {
|
||||
var u User
|
||||
if err := c.getJSON(ctx, token, "/users/@me", &u); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if u.ID == "" {
|
||||
return nil, fmt.Errorf("%w: user response without id", ErrUpstream)
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
// GetGuilds returns all guilds of the authorized user
|
||||
// (GET /users/@me/guilds), following the after= pagination.
|
||||
func (c *Client) GetGuilds(ctx context.Context, token string) ([]Guild, error) {
|
||||
var all []Guild
|
||||
after := ""
|
||||
for page := 0; page < maxGuildPages; page++ {
|
||||
q := url.Values{"limit": {fmt.Sprint(guildPageSize)}}
|
||||
if after != "" {
|
||||
q.Set("after", after)
|
||||
}
|
||||
var batch []Guild
|
||||
if err := c.getJSON(ctx, token, "/users/@me/guilds?"+q.Encode(), &batch); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
all = append(all, batch...)
|
||||
if len(batch) < guildPageSize {
|
||||
break
|
||||
}
|
||||
after = batch[len(batch)-1].ID
|
||||
}
|
||||
return all, nil
|
||||
}
|
||||
|
||||
// IsMember reports whether guildID is in guilds.
|
||||
func IsMember(guilds []Guild, guildID string) bool {
|
||||
if guildID == "" {
|
||||
return false
|
||||
}
|
||||
for _, g := range guilds {
|
||||
if g.ID == guildID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *Client) getJSON(ctx context.Context, token, path string, out any) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.APIBase+path, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: %v", ErrUpstream, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("%w: GET %s returned %d", ErrUpstream, strings.SplitN(path, "?", 2)[0], resp.StatusCode)
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(resp.Body, maxBodyBytes)).Decode(out); err != nil {
|
||||
return fmt.Errorf("%w: decode %s: %v", ErrUpstream, path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAuthCodeURL(t *testing.T) {
|
||||
c := &Client{AuthorizeURL: "https://discord.example/oauth2/authorize"}
|
||||
raw := c.AuthCodeURL(testClientID, "https://cloud.example.com/oauth2/discord/callback", "st")
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if u.Host != "discord.example" || u.Path != "/oauth2/authorize" {
|
||||
t.Fatalf("unexpected authorize url %s", raw)
|
||||
}
|
||||
want := map[string]string{
|
||||
"response_type": "code",
|
||||
"client_id": testClientID,
|
||||
"redirect_uri": "https://cloud.example.com/oauth2/discord/callback",
|
||||
"scope": "identify email guilds",
|
||||
"state": "st",
|
||||
}
|
||||
for k, v := range want {
|
||||
if got := u.Query().Get(k); got != v {
|
||||
t.Errorf("%s = %q, want %q", k, got, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExchange(t *testing.T) {
|
||||
fd := newFakeDiscord(t)
|
||||
c := fd.client()
|
||||
ctx := context.Background()
|
||||
|
||||
tok, err := c.Exchange(ctx, testClientID, testSecret, testCode, "https://cb")
|
||||
if err != nil || tok != testToken {
|
||||
t.Fatalf("Exchange = %q, %v", tok, err)
|
||||
}
|
||||
if _, err := c.Exchange(ctx, testClientID, testSecret, "wrong-code", "https://cb"); !errors.Is(err, ErrInvalidGrant) {
|
||||
t.Errorf("invalid code: err = %v, want ErrInvalidGrant", err)
|
||||
}
|
||||
if _, err := c.Exchange(ctx, testClientID, "wrong-secret", testCode, "https://cb"); !errors.Is(err, ErrInvalidClient) {
|
||||
t.Errorf("invalid secret: err = %v, want ErrInvalidClient", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetUser(t *testing.T) {
|
||||
fd := newFakeDiscord(t)
|
||||
c := fd.client()
|
||||
u, err := c.GetUser(context.Background(), testToken)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if u.ID != fd.user.ID || u.Username != "alice" || u.Email != "alice@example.com" || !u.Verified {
|
||||
t.Errorf("unexpected user %+v", u)
|
||||
}
|
||||
if _, err := c.GetUser(context.Background(), "bad-token"); !errors.Is(err, ErrUpstream) {
|
||||
t.Errorf("bad token: err = %v, want ErrUpstream", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetGuildsFollowsPagination(t *testing.T) {
|
||||
fd := newFakeDiscord(t)
|
||||
fd.guilds = manyGuilds(450)
|
||||
gs, err := fd.client().GetGuilds(context.Background(), testToken)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(gs) != 450 || gs[449].ID != fd.guilds[449].ID {
|
||||
t.Fatalf("got %d guilds", len(gs))
|
||||
}
|
||||
if fd.guildCalls != 3 {
|
||||
t.Errorf("guild requests = %d, want 3", fd.guildCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetGuildsUpstreamError(t *testing.T) {
|
||||
fd := newFakeDiscord(t)
|
||||
fd.guildsStatus = http.StatusInternalServerError
|
||||
if _, err := fd.client().GetGuilds(context.Background(), testToken); !errors.Is(err, ErrUpstream) {
|
||||
t.Errorf("err = %v, want ErrUpstream", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsMember(t *testing.T) {
|
||||
gs := []Guild{{ID: "100000000000000001"}, {ID: "100000000000000002"}}
|
||||
if !IsMember(gs, "100000000000000002") {
|
||||
t.Error("member not detected")
|
||||
}
|
||||
if IsMember(gs, "100000000000000003") {
|
||||
t.Error("non member accepted")
|
||||
}
|
||||
if IsMember(gs, "") {
|
||||
t.Error("empty guild id accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserHelpers(t *testing.T) {
|
||||
u := User{Username: "alice", Email: " a@example.com "}
|
||||
if u.DisplayName() != "alice" {
|
||||
t.Errorf("DisplayName fallback = %q", u.DisplayName())
|
||||
}
|
||||
if u.VerifiedEmail() != "" {
|
||||
t.Error("unverified email returned")
|
||||
}
|
||||
u.GlobalName, u.Verified = "Alice", true
|
||||
if u.DisplayName() != "Alice" || u.VerifiedEmail() != "a@example.com" {
|
||||
t.Errorf("got %q %q", u.DisplayName(), u.VerifiedEmail())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const (
|
||||
testClientID = "123456789012345678"
|
||||
testSecret = "test-client-secret"
|
||||
testCode = "valid-code"
|
||||
testToken = "discord-access-token"
|
||||
)
|
||||
|
||||
// fakeDiscord mocks the Discord OAuth2 token endpoint and the REST API
|
||||
// endpoints /users/@me and /users/@me/guilds.
|
||||
type fakeDiscord struct {
|
||||
srv *httptest.Server
|
||||
|
||||
mu sync.Mutex
|
||||
user User
|
||||
guilds []Guild
|
||||
guildsStatus int
|
||||
tokenCalls int
|
||||
guildCalls int
|
||||
}
|
||||
|
||||
func newFakeDiscord(t *testing.T) *fakeDiscord {
|
||||
t.Helper()
|
||||
f := &fakeDiscord{
|
||||
user: User{
|
||||
ID: "111111111111111111",
|
||||
Username: "alice",
|
||||
GlobalName: "Alice",
|
||||
Email: "alice@example.com",
|
||||
Verified: true,
|
||||
},
|
||||
guildsStatus: http.StatusOK,
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/oauth2/token", f.token)
|
||||
mux.HandleFunc("/users/@me", f.authed(f.me))
|
||||
mux.HandleFunc("/users/@me/guilds", f.authed(f.listGuilds))
|
||||
f.srv = httptest.NewServer(mux)
|
||||
t.Cleanup(f.srv.Close)
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *fakeDiscord) client() *Client {
|
||||
return &Client{
|
||||
HTTP: f.srv.Client(),
|
||||
APIBase: f.srv.URL,
|
||||
AuthorizeURL: f.srv.URL + "/oauth2/authorize",
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fakeDiscord) token(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
f.tokenCalls++
|
||||
f.mu.Unlock()
|
||||
if r.Method != http.MethodPost {
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
id, secret, ok := r.BasicAuth()
|
||||
if !ok || id != testClientID || secret != testSecret {
|
||||
writeTestJSON(w, http.StatusUnauthorized, map[string]string{"error": "invalid_client"})
|
||||
return
|
||||
}
|
||||
if err := r.ParseForm(); err != nil || r.PostForm.Get("grant_type") != "authorization_code" || r.PostForm.Get("redirect_uri") == "" {
|
||||
writeTestJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid_request"})
|
||||
return
|
||||
}
|
||||
if r.PostForm.Get("code") != testCode {
|
||||
writeTestJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid_grant"})
|
||||
return
|
||||
}
|
||||
writeTestJSON(w, http.StatusOK, map[string]any{
|
||||
"access_token": testToken,
|
||||
"token_type": "Bearer",
|
||||
"scope": OAuthScopes,
|
||||
})
|
||||
}
|
||||
|
||||
func (f *fakeDiscord) authed(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "Bearer "+testToken {
|
||||
writeTestJSON(w, http.StatusUnauthorized, map[string]string{"message": "401: Unauthorized"})
|
||||
return
|
||||
}
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fakeDiscord) me(w http.ResponseWriter, _ *http.Request) {
|
||||
f.mu.Lock()
|
||||
u := f.user
|
||||
f.mu.Unlock()
|
||||
writeTestJSON(w, http.StatusOK, u)
|
||||
}
|
||||
|
||||
// listGuilds implements the limit / after pagination of the Discord API.
|
||||
// f.guilds must be sorted by ID.
|
||||
func (f *fakeDiscord) listGuilds(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.guildCalls++
|
||||
if f.guildsStatus != http.StatusOK {
|
||||
w.WriteHeader(f.guildsStatus)
|
||||
return
|
||||
}
|
||||
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||
if limit <= 0 || limit > 200 {
|
||||
limit = 200
|
||||
}
|
||||
after := r.URL.Query().Get("after")
|
||||
page := []Guild{}
|
||||
for _, g := range f.guilds {
|
||||
if after != "" && g.ID <= after {
|
||||
continue
|
||||
}
|
||||
page = append(page, g)
|
||||
if len(page) == limit {
|
||||
break
|
||||
}
|
||||
}
|
||||
writeTestJSON(w, http.StatusOK, page)
|
||||
}
|
||||
|
||||
// manyGuilds returns n guilds with ascending 18 digit IDs.
|
||||
func manyGuilds(n int) []Guild {
|
||||
gs := make([]Guild, n)
|
||||
for i := range gs {
|
||||
gs[i] = Guild{ID: fmt.Sprintf("%018d", 100000000000000000+i), Name: fmt.Sprintf("guild %d", i)}
|
||||
}
|
||||
return gs
|
||||
}
|
||||
|
||||
func writeTestJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
libregraph "github.com/owncloud/libre-graph-api-go"
|
||||
)
|
||||
|
||||
// GraphClientFunc returns a LibreGraph client authenticated as the service
|
||||
// account. It is called per operation so expired tokens are refreshed.
|
||||
type GraphClientFunc func(ctx context.Context) (*libregraph.APIClient, error)
|
||||
|
||||
// GraphDirectory implements Directory with the LibreGraph users API.
|
||||
type GraphDirectory struct {
|
||||
Client GraphClientFunc
|
||||
}
|
||||
|
||||
// GetUserByName implements Directory.
|
||||
func (d GraphDirectory) GetUserByName(ctx context.Context, name string) (*libregraph.User, error) {
|
||||
c, err := d.Client(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
u, resp, err := c.UserApi.GetUser(ctx, name).Execute()
|
||||
defer closeBody(resp)
|
||||
if resp != nil && resp.StatusCode == http.StatusNotFound {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, graphError(err, resp)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// FindUsersByMail implements Directory. The Graph $search matches user name,
|
||||
// mail and display name by substring, so callers must filter exactly.
|
||||
func (d GraphDirectory) FindUsersByMail(ctx context.Context, mail string) ([]libregraph.User, error) {
|
||||
c, err := d.Client(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
quoted := `"` + strings.ReplaceAll(mail, `"`, "") + `"`
|
||||
col, resp, err := c.UsersApi.ListUsers(ctx).Search(quoted).Execute()
|
||||
defer closeBody(resp)
|
||||
if err != nil {
|
||||
return nil, graphError(err, resp)
|
||||
}
|
||||
return col.GetValue(), nil
|
||||
}
|
||||
|
||||
// CreateUser implements Directory.
|
||||
func (d GraphDirectory) CreateUser(ctx context.Context, u libregraph.User) (*libregraph.User, error) {
|
||||
c, err := d.Client(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
created, resp, err := c.UsersApi.CreateUser(ctx).User(u).Execute()
|
||||
defer closeBody(resp)
|
||||
if err != nil {
|
||||
return nil, graphError(err, resp)
|
||||
}
|
||||
return created, nil
|
||||
}
|
||||
|
||||
// UpdateUser implements Directory.
|
||||
func (d GraphDirectory) UpdateUser(ctx context.Context, id string, p UserPatch) error {
|
||||
c, err := d.Client(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
upd := libregraph.NewUserUpdate()
|
||||
if p.AccountEnabled != nil {
|
||||
upd.SetAccountEnabled(*p.AccountEnabled)
|
||||
}
|
||||
if p.DisplayName != nil {
|
||||
upd.SetDisplayName(*p.DisplayName)
|
||||
}
|
||||
if p.Mail != nil {
|
||||
upd.SetMail(*p.Mail)
|
||||
}
|
||||
if len(p.Identities) > 0 {
|
||||
upd.SetIdentities(p.Identities)
|
||||
}
|
||||
_, resp, err := c.UserApi.UpdateUser(ctx, id).UserUpdate(*upd).Execute()
|
||||
defer closeBody(resp)
|
||||
if err != nil {
|
||||
return graphError(err, resp)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteUser implements Directory.
|
||||
func (d GraphDirectory) DeleteUser(ctx context.Context, id string) error {
|
||||
c, err := d.Client(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := c.UserApi.DeleteUser(ctx, id).Execute()
|
||||
defer closeBody(resp)
|
||||
if resp != nil && resp.StatusCode == http.StatusNotFound {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return graphError(err, resp)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func closeBody(resp *http.Response) {
|
||||
if resp != nil && resp.Body != nil {
|
||||
_, _ = io.Copy(io.Discard, resp.Body)
|
||||
resp.Body.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// GraphStatusError is a Graph API error response.
|
||||
type GraphStatusError struct {
|
||||
Status int
|
||||
Body string
|
||||
}
|
||||
|
||||
func (e *GraphStatusError) Error() string {
|
||||
return fmt.Sprintf("graph returned %d: %s", e.Status, e.Body)
|
||||
}
|
||||
|
||||
func graphError(err error, resp *http.Response) error {
|
||||
var oe libregraph.GenericOpenAPIError
|
||||
if errors.As(err, &oe) && len(oe.Body()) > 0 {
|
||||
body := oe.Body()
|
||||
if len(body) > 512 {
|
||||
body = body[:512]
|
||||
}
|
||||
if resp != nil {
|
||||
return &GraphStatusError{Status: resp.StatusCode, Body: string(body)}
|
||||
}
|
||||
return fmt.Errorf("graph error: %s", body)
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
)
|
||||
|
||||
// Error codes passed to the Renderer. They select the user facing message.
|
||||
const (
|
||||
ErrCodeDisabled = "discord_disabled"
|
||||
ErrCodeInvalidState = "discord_invalid_state"
|
||||
ErrCodeExpired = "discord_state_expired"
|
||||
ErrCodeInvalidCode = "discord_invalid_code"
|
||||
ErrCodeCancelled = "discord_cancelled"
|
||||
ErrCodeNotMember = "discord_not_member"
|
||||
ErrCodeUpstream = "discord_upstream"
|
||||
ErrCodeProvision = "discord_provision_failed"
|
||||
ErrCodeServer = "discord_server_error"
|
||||
|
||||
ErrCodeUsernameInvalid = "discord_username_invalid"
|
||||
ErrCodeUsernameTaken = "discord_username_taken"
|
||||
|
||||
// ErrCodeLinkConflict means the Discord user is linked to another
|
||||
// account, or the account is linked to another Discord user.
|
||||
ErrCodeLinkConflict = "discord_link_conflict"
|
||||
|
||||
// ErrCodeRegistrationClosed means new accounts cannot be created this way.
|
||||
ErrCodeRegistrationClosed = "registration_closed"
|
||||
// ErrCodePendingApproval means the account waits for an admin's approval.
|
||||
ErrCodePendingApproval = "registration_pending"
|
||||
// ErrCodeRegistrationSubmitted is shown right after a pending signup.
|
||||
ErrCodeRegistrationSubmitted = "registration_submitted"
|
||||
)
|
||||
|
||||
const maxQueryLen = 4096
|
||||
|
||||
// API is the Discord API used by the handler. *Client implements it.
|
||||
type API interface {
|
||||
AuthCodeURL(clientID, redirectURI, state string) string
|
||||
Exchange(ctx context.Context, clientID, clientSecret, code, redirectURI string) (string, error)
|
||||
GetUser(ctx context.Context, token string) (*User, error)
|
||||
GetGuilds(ctx context.Context, token string) ([]Guild, error)
|
||||
}
|
||||
|
||||
// Provisioner finds, creates and links the oCIS account for a Discord user.
|
||||
type Provisioner interface {
|
||||
// Lookup returns the oCIS user ID of the account for u, or "" when no
|
||||
// account exists yet.
|
||||
Lookup(ctx context.Context, u *User) (string, error)
|
||||
// Create creates the account for u with the chosen username and returns
|
||||
// its oCIS user ID. It returns ErrUsernameInvalid or ErrUsernameTaken
|
||||
// when the username cannot be used.
|
||||
// enabled=false creates the account disabled (pending approval).
|
||||
Create(ctx context.Context, u *User, username string, enabled bool) (string, error)
|
||||
// Link links u to the existing account userID. It returns
|
||||
// ErrIdentityConflict when either side is linked to someone else.
|
||||
Link(ctx context.Context, userID string, u *User) error
|
||||
// Linked reports whether the account userID is linked to Discord.
|
||||
Linked(ctx context.Context, userID string) (bool, error)
|
||||
}
|
||||
|
||||
// SessionIssuer writes the regular idp logon cookie for an oCIS user ID.
|
||||
type SessionIssuer interface {
|
||||
IssueLogon(ctx context.Context, w http.ResponseWriter, userID string) error
|
||||
}
|
||||
|
||||
// AdminAuthorizer checks that the request comes from a user that may manage
|
||||
// settings. It returns the HTTP status to answer with when access is denied.
|
||||
type AdminAuthorizer interface {
|
||||
AuthorizeAdmin(r *http.Request) (int, error)
|
||||
}
|
||||
|
||||
// Renderer renders the HTML pages of the login flow.
|
||||
type Renderer interface {
|
||||
// Error renders an error page with the given status and error code.
|
||||
Error(w http.ResponseWriter, r *http.Request, status int, code string)
|
||||
// Continue renders a same-origin page that navigates to target. A page is
|
||||
// needed because the logon cookie is SameSite=Strict and would not be sent
|
||||
// on a redirect chain that started on discord.com.
|
||||
Continue(w http.ResponseWriter, r *http.Request, target string)
|
||||
// Signup renders the form where a new user chooses the username.
|
||||
Signup(w http.ResponseWriter, r *http.Request, status int, f SignupForm)
|
||||
// Register renders the web registration form.
|
||||
Register(w http.ResponseWriter, r *http.Request, status int, f RegisterForm)
|
||||
}
|
||||
|
||||
// Options configures the Handler.
|
||||
type Options struct {
|
||||
Store *Store
|
||||
Registration *RegistrationStore
|
||||
Pending *PendingStore
|
||||
Accounts Accounts
|
||||
WebAccounts WebAccounts
|
||||
API API
|
||||
Provisioner Provisioner
|
||||
Sessions SessionIssuer
|
||||
Admin AdminAuthorizer
|
||||
Users UserAuthenticator
|
||||
Render Renderer
|
||||
Logger log.Logger
|
||||
|
||||
// PublicURL is the external oCIS URL, e.g. https://cloud.example.com.
|
||||
PublicURL string
|
||||
// AuthorizePath is the lico authorize endpoint path.
|
||||
AuthorizePath string
|
||||
// MustBeSignedIn is the value lico expects in the identifier= parameter.
|
||||
MustBeSignedIn string
|
||||
// StateKey signs the state cookie.
|
||||
StateKey []byte
|
||||
// Now is used in tests. Defaults to time.Now.
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
// Handler serves the /oauth2/discord routes.
|
||||
type Handler struct {
|
||||
opt Options
|
||||
state stateCodec
|
||||
}
|
||||
|
||||
// NewHandler returns a Handler.
|
||||
func NewHandler(opt Options) (*Handler, error) {
|
||||
switch {
|
||||
case opt.Store == nil, opt.Registration == nil, opt.Pending == nil, opt.Accounts == nil, opt.WebAccounts == nil, opt.API == nil, opt.Provisioner == nil, opt.Sessions == nil, opt.Admin == nil, opt.Users == nil, opt.Render == nil:
|
||||
return nil, errors.New("discord handler: missing dependency")
|
||||
case len(opt.StateKey) < 32:
|
||||
return nil, errors.New("discord handler: state key must be at least 32 bytes")
|
||||
case opt.PublicURL == "" || opt.AuthorizePath == "":
|
||||
return nil, errors.New("discord handler: public url and authorize path are required")
|
||||
}
|
||||
if opt.Now == nil {
|
||||
opt.Now = time.Now
|
||||
}
|
||||
return &Handler{opt: opt, state: stateCodec{key: opt.StateKey, now: opt.Now}}, nil
|
||||
}
|
||||
|
||||
// RoutePrefix is the path prefix served by the handler.
|
||||
func RoutePrefix() string { return routePrefix }
|
||||
|
||||
// RedirectURI is the OAuth2 callback URL to register in the Discord developer portal.
|
||||
func (h *Handler) RedirectURI() string {
|
||||
return strings.TrimRight(h.opt.PublicURL, "/") + routePrefix + "/callback"
|
||||
}
|
||||
|
||||
// Enabled reports whether the login button should be shown.
|
||||
func (h *Handler) Enabled() bool { return h.opt.Store.Get().Ready() }
|
||||
|
||||
// Mount registers the routes on r.
|
||||
func (h *Handler) Mount(r chi.Router) {
|
||||
r.Route(routePrefix, func(r chi.Router) {
|
||||
r.Get("/login", h.login)
|
||||
r.Get("/callback", h.callback)
|
||||
r.Post("/signup", h.signup)
|
||||
r.Get("/account/link", h.getLink)
|
||||
r.Post("/account/link", h.startLink)
|
||||
r.Get("/registration", h.getPublicRegistration)
|
||||
r.Get("/admin/settings", h.getSettings)
|
||||
r.Put("/admin/settings", h.putSettings)
|
||||
r.Get("/admin/registration", h.getRegistration)
|
||||
r.Put("/admin/registration", h.putRegistration)
|
||||
r.Get("/admin/pending", h.listPending)
|
||||
r.Post("/admin/pending/{id}/approve", h.approvePending)
|
||||
r.Post("/admin/pending/{id}/reject", h.rejectPending)
|
||||
r.Get("/register", h.getRegister)
|
||||
r.Post("/register", h.postRegister)
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) login(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.opt.Store.Get().Ready() {
|
||||
h.opt.Render.Error(w, r, http.StatusNotFound, ErrCodeDisabled)
|
||||
return
|
||||
}
|
||||
if len(r.URL.RawQuery) > maxQueryLen {
|
||||
h.opt.Render.Error(w, r, http.StatusBadRequest, ErrCodeInvalidState)
|
||||
return
|
||||
}
|
||||
target, err := h.beginAuthorization(w, stateData{Query: r.URL.RawQuery})
|
||||
if err != nil {
|
||||
h.opt.Logger.Error().Err(err).Msg("discord: could not start authorization")
|
||||
h.opt.Render.Error(w, r, http.StatusInternalServerError, ErrCodeServer)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, target, http.StatusFound)
|
||||
}
|
||||
|
||||
// beginAuthorization sets the state cookie for sd and returns the Discord
|
||||
// authorization URL.
|
||||
func (h *Handler) beginAuthorization(w http.ResponseWriter, sd stateData) (string, error) {
|
||||
state, err := randomToken(32)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
sd.State = state
|
||||
sd.Exp = h.opt.Now().Add(stateTTL).Unix()
|
||||
value, err := h.state.encode(sd)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
http.SetCookie(w, h.stateCookie(value, int(stateTTL/time.Second)))
|
||||
return h.opt.API.AuthCodeURL(h.opt.Store.Get().ClientID, h.RedirectURI(), state), nil
|
||||
}
|
||||
|
||||
func (h *Handler) callback(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
q := r.URL.Query()
|
||||
logger := h.opt.Logger.With().Str("component", "discord").Logger()
|
||||
|
||||
// The state cookie is single use.
|
||||
http.SetCookie(w, h.stateCookie("", -1))
|
||||
|
||||
c, err := r.Cookie(stateCookieName)
|
||||
if err != nil {
|
||||
h.opt.Render.Error(w, r, http.StatusBadRequest, ErrCodeInvalidState)
|
||||
return
|
||||
}
|
||||
sd, err := h.state.decode(c.Value, q.Get("state"))
|
||||
switch {
|
||||
case errors.Is(err, errStateExpired):
|
||||
h.opt.Render.Error(w, r, http.StatusBadRequest, ErrCodeExpired)
|
||||
return
|
||||
case err != nil:
|
||||
logger.Info().Msg("discord callback with invalid state")
|
||||
h.opt.Render.Error(w, r, http.StatusBadRequest, ErrCodeInvalidState)
|
||||
return
|
||||
}
|
||||
|
||||
// From here on the link flow reports failures on the account page.
|
||||
fail := func(status int, code string) {
|
||||
if sd.Mode == modeLink {
|
||||
h.linkResult(w, r, code)
|
||||
return
|
||||
}
|
||||
h.opt.Render.Error(w, r, status, code)
|
||||
}
|
||||
|
||||
if e := q.Get("error"); e != "" {
|
||||
logger.Debug().Str("error", e).Msg("discord authorization not granted")
|
||||
fail(http.StatusForbidden, ErrCodeCancelled)
|
||||
return
|
||||
}
|
||||
code := q.Get("code")
|
||||
if code == "" {
|
||||
fail(http.StatusBadRequest, ErrCodeInvalidCode)
|
||||
return
|
||||
}
|
||||
|
||||
s := h.opt.Store.Get()
|
||||
if !s.Ready() {
|
||||
fail(http.StatusNotFound, ErrCodeDisabled)
|
||||
return
|
||||
}
|
||||
|
||||
token, err := h.opt.API.Exchange(ctx, s.ClientID, s.ClientSecret, code, h.RedirectURI())
|
||||
switch {
|
||||
case errors.Is(err, ErrInvalidGrant):
|
||||
fail(http.StatusBadRequest, ErrCodeInvalidCode)
|
||||
return
|
||||
case err != nil:
|
||||
logger.Error().Err(err).Msg("discord token exchange failed")
|
||||
fail(http.StatusBadGateway, ErrCodeUpstream)
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.opt.API.GetUser(ctx, token)
|
||||
if err != nil {
|
||||
logger.Error().Err(err).Msg("discord get user failed")
|
||||
fail(http.StatusBadGateway, ErrCodeUpstream)
|
||||
return
|
||||
}
|
||||
guilds, err := h.opt.API.GetGuilds(ctx, token)
|
||||
if err != nil {
|
||||
logger.Error().Err(err).Msg("discord get guilds failed")
|
||||
fail(http.StatusBadGateway, ErrCodeUpstream)
|
||||
return
|
||||
}
|
||||
if !IsMember(guilds, s.AllowedGuildID) {
|
||||
logger.Info().Str("discord_id", user.ID).Msg("discord user is not a member of the allowed guild")
|
||||
fail(http.StatusForbidden, ErrCodeNotMember)
|
||||
return
|
||||
}
|
||||
|
||||
if sd.Mode == modeLink {
|
||||
h.finishLink(w, r, sd.UserID, user)
|
||||
return
|
||||
}
|
||||
|
||||
userID, err := h.opt.Provisioner.Lookup(ctx, user)
|
||||
if err != nil {
|
||||
logger.Error().Err(err).Str("discord_id", user.ID).Msg("discord user lookup failed")
|
||||
h.opt.Render.Error(w, r, http.StatusInternalServerError, ErrCodeProvision)
|
||||
return
|
||||
}
|
||||
if userID == "" {
|
||||
if !h.opt.Registration.Get().DiscordAllowed() {
|
||||
h.opt.Render.Error(w, r, http.StatusForbidden, ErrCodeRegistrationClosed)
|
||||
return
|
||||
}
|
||||
// No account yet: let the user choose the username first.
|
||||
h.startSignup(w, r, user, sd.Query)
|
||||
return
|
||||
}
|
||||
if h.opt.Pending.IsPending(userID) {
|
||||
h.opt.Render.Error(w, r, http.StatusForbidden, ErrCodePendingApproval)
|
||||
return
|
||||
}
|
||||
if err := h.opt.Sessions.IssueLogon(ctx, w, userID); err != nil {
|
||||
logger.Error().Err(err).Str("user_id", userID).Msg("discord logon cookie failed")
|
||||
h.opt.Render.Error(w, r, http.StatusInternalServerError, ErrCodeServer)
|
||||
return
|
||||
}
|
||||
|
||||
h.opt.Render.Continue(w, r, h.continueTarget(sd.Query))
|
||||
}
|
||||
|
||||
// continueTarget returns where the browser goes after a successful logon.
|
||||
// With an OIDC authorize request it resumes that request; otherwise the web
|
||||
// UI is opened, which starts a fresh OIDC flow that finds the logon cookie.
|
||||
func (h *Handler) continueTarget(rawQuery string) string {
|
||||
q, err := url.ParseQuery(rawQuery)
|
||||
if err != nil || q.Get("client_id") == "" {
|
||||
return "/"
|
||||
}
|
||||
q.Del("flow")
|
||||
var prompts []string
|
||||
for _, p := range strings.Fields(q.Get("prompt")) {
|
||||
if p != "login" && p != "select_account" {
|
||||
prompts = append(prompts, p)
|
||||
}
|
||||
}
|
||||
if len(prompts) > 0 {
|
||||
q.Set("prompt", strings.Join(prompts, " "))
|
||||
} else {
|
||||
q.Del("prompt")
|
||||
}
|
||||
if h.opt.MustBeSignedIn != "" {
|
||||
q.Set("identifier", h.opt.MustBeSignedIn)
|
||||
}
|
||||
return h.opt.AuthorizePath + "?" + q.Encode()
|
||||
}
|
||||
|
||||
func (h *Handler) stateCookie(value string, maxAge int) *http.Cookie {
|
||||
return &http.Cookie{
|
||||
Name: stateCookieName,
|
||||
Value: value,
|
||||
Path: routePrefix + "/",
|
||||
MaxAge: maxAge,
|
||||
Secure: true,
|
||||
HttpOnly: true,
|
||||
// Lax: the cookie must be sent on the top level navigation back from discord.com.
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) getSettings(w http.ResponseWriter, r *http.Request) {
|
||||
if status, err := h.opt.Admin.AuthorizeAdmin(r); err != nil {
|
||||
writeJSONError(w, status, "accessDenied", "", http.StatusText(status))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, h.opt.Store.Get().View(h.RedirectURI()))
|
||||
}
|
||||
|
||||
func (h *Handler) putSettings(w http.ResponseWriter, r *http.Request) {
|
||||
if status, err := h.opt.Admin.AuthorizeAdmin(r); err != nil {
|
||||
writeJSONError(w, status, "accessDenied", "", http.StatusText(status))
|
||||
return
|
||||
}
|
||||
dec := json.NewDecoder(io.LimitReader(r.Body, 64<<10))
|
||||
dec.DisallowUnknownFields()
|
||||
var u Update
|
||||
if err := dec.Decode(&u); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "invalidRequest", "", "invalid JSON body")
|
||||
return
|
||||
}
|
||||
next := u.Apply(h.opt.Store.Get())
|
||||
if err := h.opt.Store.Save(next); err != nil {
|
||||
var ve *ValidationError
|
||||
if errors.As(err, &ve) {
|
||||
writeJSONError(w, http.StatusBadRequest, "invalidRequest", ve.Field, ve.Message)
|
||||
return
|
||||
}
|
||||
h.opt.Logger.Error().Err(err).Msg("discord: could not save settings")
|
||||
writeJSONError(w, http.StatusInternalServerError, "generalException", "", "could not save settings")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, next.View(h.RedirectURI()))
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
func writeJSONError(w http.ResponseWriter, status int, code, field, message string) {
|
||||
type body struct {
|
||||
Code string `json:"code"`
|
||||
Field string `json:"field,omitempty"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
writeJSON(w, status, map[string]body{"error": {Code: code, Field: field, Message: message}})
|
||||
}
|
||||
@@ -0,0 +1,585 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
)
|
||||
|
||||
const (
|
||||
testPublicURL = "https://cloud.example.com/"
|
||||
testAuthorizePath = "/signin/v1/identifier/_/authorize"
|
||||
testGuildID = "100000000000000002"
|
||||
)
|
||||
|
||||
type fakeRenderer struct {
|
||||
status int
|
||||
code string
|
||||
target string
|
||||
signup *SignupForm
|
||||
register *RegisterForm
|
||||
}
|
||||
|
||||
func (f *fakeRenderer) Register(w http.ResponseWriter, _ *http.Request, status int, form RegisterForm) {
|
||||
f.status, f.register = status, &form
|
||||
w.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (f *fakeRenderer) Signup(w http.ResponseWriter, _ *http.Request, status int, form SignupForm) {
|
||||
f.status, f.signup = status, &form
|
||||
w.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (f *fakeRenderer) Error(w http.ResponseWriter, _ *http.Request, status int, code string) {
|
||||
f.status, f.code = status, code
|
||||
w.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (f *fakeRenderer) Continue(w http.ResponseWriter, _ *http.Request, target string) {
|
||||
f.status, f.target = http.StatusOK, target
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
type fakeProvisioner struct {
|
||||
calls int
|
||||
user *User
|
||||
id string
|
||||
err error
|
||||
// missing makes Lookup report that no account exists.
|
||||
missing bool
|
||||
created []string
|
||||
createErr error
|
||||
// createdEnabled records the enabled flag of each Create call.
|
||||
createdEnabled []bool
|
||||
// link flow
|
||||
linkErr error
|
||||
linkedID string
|
||||
linkedUser *User
|
||||
isLinked bool
|
||||
linkedErr error
|
||||
}
|
||||
|
||||
func (f *fakeProvisioner) Lookup(_ context.Context, u *User) (string, error) {
|
||||
f.calls++
|
||||
f.user = u
|
||||
if f.err != nil {
|
||||
return "", f.err
|
||||
}
|
||||
if f.missing {
|
||||
return "", nil
|
||||
}
|
||||
return f.id, nil
|
||||
}
|
||||
|
||||
func (f *fakeProvisioner) Create(_ context.Context, u *User, username string, enabled bool) (string, error) {
|
||||
f.user = u
|
||||
f.createdEnabled = append(f.createdEnabled, enabled)
|
||||
if f.createErr != nil {
|
||||
return "", f.createErr
|
||||
}
|
||||
f.created = append(f.created, username)
|
||||
f.missing = false
|
||||
return f.id, nil
|
||||
}
|
||||
|
||||
type fakeSessions struct {
|
||||
userID string
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeSessions) IssueLogon(_ context.Context, w http.ResponseWriter, id string) error {
|
||||
if f.err != nil {
|
||||
return f.err
|
||||
}
|
||||
f.userID = id
|
||||
http.SetCookie(w, &http.Cookie{Name: "__Secure-KKT", Value: "logon"})
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeAdmin struct{ status int }
|
||||
|
||||
func (f *fakeAdmin) AuthorizeAdmin(*http.Request) (int, error) {
|
||||
if f.status == http.StatusOK {
|
||||
return http.StatusOK, nil
|
||||
}
|
||||
return f.status, errors.New("denied")
|
||||
}
|
||||
|
||||
type harness struct {
|
||||
t *testing.T
|
||||
fd *fakeDiscord
|
||||
store *Store
|
||||
reg *RegistrationStore
|
||||
pending *PendingStore
|
||||
accounts *fakeAccounts
|
||||
web *fakeWeb
|
||||
render *fakeRenderer
|
||||
prov *fakeProvisioner
|
||||
sess *fakeSessions
|
||||
admin *fakeAdmin
|
||||
users *fakeUsers
|
||||
now time.Time
|
||||
handler *Handler
|
||||
router chi.Router
|
||||
}
|
||||
|
||||
func newHarness(t *testing.T) *harness {
|
||||
t.Helper()
|
||||
h := &harness{
|
||||
t: t,
|
||||
fd: newFakeDiscord(t),
|
||||
render: &fakeRenderer{},
|
||||
prov: &fakeProvisioner{id: "4c510ada-c86b-4815-8820-42cdf82c3d51"},
|
||||
sess: &fakeSessions{},
|
||||
admin: &fakeAdmin{status: http.StatusOK},
|
||||
users: &fakeUsers{id: "9d7c1a52-0000-4000-8000-000000000001", status: http.StatusOK},
|
||||
now: time.Unix(1700000000, 0),
|
||||
}
|
||||
h.fd.guilds = []Guild{{ID: "100000000000000001"}, {ID: testGuildID}}
|
||||
|
||||
st, err := NewStore(filepath.Join(t.TempDir(), "discord.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := validSettings()
|
||||
s.AllowedGuildID = testGuildID
|
||||
if err := st.Save(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.store = st
|
||||
reg, err := NewRegistrationStore(filepath.Join(t.TempDir(), "registration.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.reg = reg
|
||||
pending, err := NewPendingStore(filepath.Join(t.TempDir(), "pending.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.pending = pending
|
||||
h.accounts = &fakeAccounts{}
|
||||
h.web = &fakeWeb{id: "7a1b2c3d-0000-4000-8000-000000000002"}
|
||||
|
||||
h.handler, err = NewHandler(Options{
|
||||
Store: st,
|
||||
Registration: reg,
|
||||
Pending: pending,
|
||||
Accounts: h.accounts,
|
||||
WebAccounts: h.web,
|
||||
API: h.fd.client(),
|
||||
Provisioner: h.prov,
|
||||
Sessions: h.sess,
|
||||
Admin: h.admin,
|
||||
Users: h.users,
|
||||
Render: h.render,
|
||||
Logger: log.NopLogger(),
|
||||
PublicURL: testPublicURL,
|
||||
AuthorizePath: testAuthorizePath,
|
||||
MustBeSignedIn: "must",
|
||||
StateKey: []byte(strings.Repeat("k", 32)),
|
||||
Now: func() time.Time { return h.now },
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := chi.NewRouter()
|
||||
h.handler.Mount(r)
|
||||
h.router = r
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *harness) do(method, target string, body io.Reader, cookies ...*http.Cookie) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(method, target, body)
|
||||
for _, c := range cookies {
|
||||
req.AddCookie(c)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
h.router.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
// login starts the flow and returns the state sent to Discord and the state cookie.
|
||||
func (h *harness) login(query string) (string, *http.Cookie) {
|
||||
h.t.Helper()
|
||||
rec := h.do(http.MethodGet, "/oauth2/discord/login?"+query, nil)
|
||||
if rec.Code != http.StatusFound {
|
||||
h.t.Fatalf("login status = %d, want 302", rec.Code)
|
||||
}
|
||||
loc, err := url.Parse(rec.Header().Get("Location"))
|
||||
if err != nil {
|
||||
h.t.Fatal(err)
|
||||
}
|
||||
var c *http.Cookie
|
||||
for _, ck := range rec.Result().Cookies() {
|
||||
if ck.Name == stateCookieName {
|
||||
c = ck
|
||||
}
|
||||
}
|
||||
state := loc.Query().Get("state")
|
||||
if state == "" || c == nil {
|
||||
h.t.Fatalf("login did not set state (state=%q cookie=%v)", state, c)
|
||||
}
|
||||
return state, c
|
||||
}
|
||||
|
||||
func (h *harness) callback(query string, cookies ...*http.Cookie) *httptest.ResponseRecorder {
|
||||
return h.do(http.MethodGet, "/oauth2/discord/callback?"+query, nil, cookies...)
|
||||
}
|
||||
|
||||
func cbQuery(code, state string) string {
|
||||
return url.Values{"code": {code}, "state": {state}}.Encode()
|
||||
}
|
||||
|
||||
func TestLoginRedirectsToDiscord(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
rec := h.do(http.MethodGet, "/oauth2/discord/login?client_id=web", nil)
|
||||
if rec.Code != http.StatusFound {
|
||||
t.Fatalf("status = %d", rec.Code)
|
||||
}
|
||||
loc, _ := url.Parse(rec.Header().Get("Location"))
|
||||
if !strings.HasPrefix(loc.String(), h.fd.srv.URL+"/oauth2/authorize") {
|
||||
t.Errorf("redirect to %s", loc)
|
||||
}
|
||||
q := loc.Query()
|
||||
if q.Get("scope") != "identify email guilds" || q.Get("client_id") != testClientID {
|
||||
t.Errorf("unexpected query %v", q)
|
||||
}
|
||||
if q.Get("redirect_uri") != "https://cloud.example.com/oauth2/discord/callback" {
|
||||
t.Errorf("redirect_uri = %q", q.Get("redirect_uri"))
|
||||
}
|
||||
var c *http.Cookie
|
||||
for _, ck := range rec.Result().Cookies() {
|
||||
if ck.Name == stateCookieName {
|
||||
c = ck
|
||||
}
|
||||
}
|
||||
if c == nil || !c.HttpOnly || !c.Secure || c.SameSite != http.SameSiteLaxMode || c.Path != "/oauth2/discord/" {
|
||||
t.Errorf("unexpected state cookie %+v", c)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallbackMemberSucceeds(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
state, c := h.login("client_id=web&state=oidc-state&flow=oidc&prompt=select_account+login&redirect_uri=https%3A%2F%2Fcloud.example.com%2Foidc-callback.html")
|
||||
rec := h.callback(cbQuery(testCode, state), c)
|
||||
|
||||
if rec.Code != http.StatusOK || h.render.code != "" {
|
||||
t.Fatalf("status = %d code = %q", rec.Code, h.render.code)
|
||||
}
|
||||
if h.prov.calls != 1 || h.prov.user.ID != h.fd.user.ID {
|
||||
t.Fatalf("provisioner calls = %d user = %+v", h.prov.calls, h.prov.user)
|
||||
}
|
||||
if h.sess.userID != h.prov.id {
|
||||
t.Errorf("logon issued for %q, want %q", h.sess.userID, h.prov.id)
|
||||
}
|
||||
|
||||
target, err := url.Parse(h.render.target)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if target.Path != testAuthorizePath {
|
||||
t.Errorf("target path = %q", target.Path)
|
||||
}
|
||||
tq := target.Query()
|
||||
if tq.Get("client_id") != "web" || tq.Get("state") != "oidc-state" || tq.Get("identifier") != "must" {
|
||||
t.Errorf("target query = %v", tq)
|
||||
}
|
||||
if tq.Has("flow") || tq.Has("prompt") {
|
||||
t.Errorf("flow/prompt must be removed: %v", tq)
|
||||
}
|
||||
|
||||
cleared := false
|
||||
for _, ck := range rec.Result().Cookies() {
|
||||
if ck.Name == stateCookieName && ck.MaxAge < 0 {
|
||||
cleared = true
|
||||
}
|
||||
}
|
||||
if !cleared {
|
||||
t.Error("state cookie was not cleared")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallbackWithoutAuthorizeRequestGoesToWebUI(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
state, c := h.login("")
|
||||
h.callback(cbQuery(testCode, state), c)
|
||||
if h.render.target != "/" {
|
||||
t.Errorf("target = %q, want /", h.render.target)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallbackNotMemberIsForbidden(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.fd.guilds = []Guild{{ID: "100000000000000001"}}
|
||||
state, c := h.login("client_id=web")
|
||||
rec := h.callback(cbQuery(testCode, state), c)
|
||||
|
||||
if rec.Code != http.StatusForbidden || h.render.code != ErrCodeNotMember {
|
||||
t.Fatalf("status = %d code = %q, want 403 %s", rec.Code, h.render.code, ErrCodeNotMember)
|
||||
}
|
||||
if h.prov.calls != 0 || h.sess.userID != "" {
|
||||
t.Error("non member must not be provisioned or logged on")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallbackMemberFoundOnLaterGuildPage(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.fd.guilds = manyGuilds(250)
|
||||
if err := h.store.Save(Settings{Enabled: true, ClientID: testClientID, ClientSecret: testSecret, AllowedGuildID: h.fd.guilds[240].ID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state, c := h.login("")
|
||||
if rec := h.callback(cbQuery(testCode, state), c); rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d code = %q", rec.Code, h.render.code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallbackStateErrors(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
call func(h *harness) *httptest.ResponseRecorder
|
||||
wantCode string
|
||||
}{
|
||||
{"missing cookie", func(h *harness) *httptest.ResponseRecorder {
|
||||
state, _ := h.login("")
|
||||
return h.callback(cbQuery(testCode, state))
|
||||
}, ErrCodeInvalidState},
|
||||
{"state mismatch", func(h *harness) *httptest.ResponseRecorder {
|
||||
_, c := h.login("")
|
||||
return h.callback(cbQuery(testCode, "forged-state"), c)
|
||||
}, ErrCodeInvalidState},
|
||||
{"missing state", func(h *harness) *httptest.ResponseRecorder {
|
||||
_, c := h.login("")
|
||||
return h.callback(url.Values{"code": {testCode}}.Encode(), c)
|
||||
}, ErrCodeInvalidState},
|
||||
{"cookie of another login", func(h *harness) *httptest.ResponseRecorder {
|
||||
stateA, _ := h.login("")
|
||||
_, cookieB := h.login("")
|
||||
return h.callback(cbQuery(testCode, stateA), cookieB)
|
||||
}, ErrCodeInvalidState},
|
||||
{"tampered cookie", func(h *harness) *httptest.ResponseRecorder {
|
||||
state, c := h.login("")
|
||||
c.Value = "x" + c.Value
|
||||
return h.callback(cbQuery(testCode, state), c)
|
||||
}, ErrCodeInvalidState},
|
||||
{"expired state", func(h *harness) *httptest.ResponseRecorder {
|
||||
state, c := h.login("")
|
||||
h.now = h.now.Add(stateTTL + time.Minute)
|
||||
return h.callback(cbQuery(testCode, state), c)
|
||||
}, ErrCodeExpired},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
rec := tt.call(h)
|
||||
if rec.Code != http.StatusBadRequest || h.render.code != tt.wantCode {
|
||||
t.Fatalf("status = %d code = %q, want 400 %s", rec.Code, h.render.code, tt.wantCode)
|
||||
}
|
||||
if h.fd.tokenCalls != 0 {
|
||||
t.Error("the code must not be exchanged with an invalid state")
|
||||
}
|
||||
if h.prov.calls != 0 {
|
||||
t.Error("provisioner must not be called")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallbackCodeErrors(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
query func(state string) string
|
||||
wantStatus int
|
||||
wantCode string
|
||||
}{
|
||||
{"invalid code", func(s string) string { return cbQuery("bad-code", s) }, http.StatusBadRequest, ErrCodeInvalidCode},
|
||||
{"missing code", func(s string) string { return url.Values{"state": {s}}.Encode() }, http.StatusBadRequest, ErrCodeInvalidCode},
|
||||
{"authorization denied", func(s string) string {
|
||||
return url.Values{"state": {s}, "error": {"access_denied"}}.Encode()
|
||||
}, http.StatusForbidden, ErrCodeCancelled},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
state, c := h.login("")
|
||||
rec := h.callback(tt.query(state), c)
|
||||
if rec.Code != tt.wantStatus || h.render.code != tt.wantCode {
|
||||
t.Fatalf("status = %d code = %q, want %d %s", rec.Code, h.render.code, tt.wantStatus, tt.wantCode)
|
||||
}
|
||||
if h.prov.calls != 0 {
|
||||
t.Error("provisioner must not be called")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallbackUpstreamAndProvisionErrors(t *testing.T) {
|
||||
t.Run("guild api failure", func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.fd.guildsStatus = http.StatusInternalServerError
|
||||
state, c := h.login("")
|
||||
if rec := h.callback(cbQuery(testCode, state), c); rec.Code != http.StatusBadGateway || h.render.code != ErrCodeUpstream {
|
||||
t.Fatalf("status = %d code = %q", rec.Code, h.render.code)
|
||||
}
|
||||
})
|
||||
t.Run("provisioning failure", func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.prov.err = errors.New("graph down")
|
||||
state, c := h.login("")
|
||||
if rec := h.callback(cbQuery(testCode, state), c); rec.Code != http.StatusInternalServerError || h.render.code != ErrCodeProvision {
|
||||
t.Fatalf("status = %d code = %q", rec.Code, h.render.code)
|
||||
}
|
||||
if h.sess.userID != "" {
|
||||
t.Error("logon issued despite provisioning failure")
|
||||
}
|
||||
})
|
||||
t.Run("logon cookie failure", func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.sess.err = errors.New("backend down")
|
||||
state, c := h.login("")
|
||||
if rec := h.callback(cbQuery(testCode, state), c); rec.Code != http.StatusInternalServerError || h.render.code != ErrCodeServer {
|
||||
t.Fatalf("status = %d code = %q", rec.Code, h.render.code)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestDisabledLogin(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
if !h.handler.Enabled() {
|
||||
t.Fatal("handler should be enabled")
|
||||
}
|
||||
if err := h.store.Save(Settings{ClientID: testClientID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if h.handler.Enabled() {
|
||||
t.Fatal("handler should be disabled")
|
||||
}
|
||||
if rec := h.do(http.MethodGet, "/oauth2/discord/login", nil); rec.Code != http.StatusNotFound || h.render.code != ErrCodeDisabled {
|
||||
t.Fatalf("status = %d code = %q", rec.Code, h.render.code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminGetSettings(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
rec := h.do(http.MethodGet, "/oauth2/discord/admin/settings", nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d", rec.Code)
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), testSecret) {
|
||||
t.Fatalf("response leaks the client secret: %s", rec.Body)
|
||||
}
|
||||
var v View
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !v.Enabled || v.ClientID != testClientID || v.AllowedGuildID != testGuildID || !v.ClientSecretSet {
|
||||
t.Errorf("unexpected view %+v", v)
|
||||
}
|
||||
if v.RedirectURI != "https://cloud.example.com/oauth2/discord/callback" {
|
||||
t.Errorf("redirect_uri = %q", v.RedirectURI)
|
||||
}
|
||||
if rec.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Error("settings response must not be cached")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminAccessDenied(t *testing.T) {
|
||||
for _, status := range []int{http.StatusUnauthorized, http.StatusForbidden} {
|
||||
h := newHarness(t)
|
||||
h.admin.status = status
|
||||
before := h.store.Get()
|
||||
if rec := h.do(http.MethodGet, "/oauth2/discord/admin/settings", nil); rec.Code != status {
|
||||
t.Errorf("GET status = %d, want %d", rec.Code, status)
|
||||
}
|
||||
rec := h.do(http.MethodPut, "/oauth2/discord/admin/settings", strings.NewReader(`{"enabled":false,"client_id":"","allowed_guild_id":""}`))
|
||||
if rec.Code != status {
|
||||
t.Errorf("PUT status = %d, want %d", rec.Code, status)
|
||||
}
|
||||
if h.store.Get() != before {
|
||||
t.Error("settings changed without permission")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminPutSettings(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
body := `{"enabled":true,"client_id":"323456789012345678","allowed_guild_id":"423456789012345678"}`
|
||||
rec := h.do(http.MethodPut, "/oauth2/discord/admin/settings", strings.NewReader(body))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d body = %s", rec.Code, rec.Body)
|
||||
}
|
||||
got := h.store.Get()
|
||||
if got.ClientID != "323456789012345678" || got.AllowedGuildID != "423456789012345678" || got.ClientSecret != testSecret {
|
||||
t.Errorf("stored settings = %+v", got)
|
||||
}
|
||||
|
||||
reloaded, err := NewStore(h.store.path)
|
||||
if err != nil || reloaded.Get() != got {
|
||||
t.Errorf("settings not persisted: %+v, %v", reloaded.Get(), err)
|
||||
}
|
||||
|
||||
body = `{"enabled":true,"client_id":"323456789012345678","client_secret":"rotated","allowed_guild_id":"423456789012345678"}`
|
||||
if rec := h.do(http.MethodPut, "/oauth2/discord/admin/settings", strings.NewReader(body)); rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d", rec.Code)
|
||||
}
|
||||
if h.store.Get().ClientSecret != "rotated" {
|
||||
t.Error("client secret was not replaced")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminPutSettingsValidation(t *testing.T) {
|
||||
tests := []struct {
|
||||
name, body, field string
|
||||
}{
|
||||
{"invalid guild", `{"enabled":true,"client_id":"323456789012345678","allowed_guild_id":"my-server"}`, "allowed_guild_id"},
|
||||
{"missing client id", `{"enabled":true,"client_id":"","allowed_guild_id":"423456789012345678"}`, "client_id"},
|
||||
{"unknown field", `{"enabled":true,"guild":"1"}`, ""},
|
||||
{"not json", `enabled=true`, ""},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
before := h.store.Get()
|
||||
rec := h.do(http.MethodPut, "/oauth2/discord/admin/settings", strings.NewReader(tt.body))
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400", rec.Code)
|
||||
}
|
||||
var resp struct {
|
||||
Error struct {
|
||||
Field string `json:"field"`
|
||||
} `json:"error"`
|
||||
}
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &resp)
|
||||
if resp.Error.Field != tt.field {
|
||||
t.Errorf("field = %q, want %q", resp.Error.Field, tt.field)
|
||||
}
|
||||
if h.store.Get() != before {
|
||||
t.Error("invalid update was applied")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewHandlerRequiresDependencies(t *testing.T) {
|
||||
if _, err := NewHandler(Options{}); err == nil {
|
||||
t.Error("expected error for missing dependencies")
|
||||
}
|
||||
h := newHarness(t)
|
||||
opt := h.handler.opt
|
||||
opt.StateKey = []byte("short")
|
||||
if _, err := NewHandler(opt); err == nil {
|
||||
t.Error("expected error for a short state key")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-ldap/ldap/v3"
|
||||
)
|
||||
|
||||
// identitiesAttribute stores the Graph identities of a user as
|
||||
// "signInType $ issuer $ issuerAssignedId".
|
||||
const identitiesAttribute = "oCExternalIdentity"
|
||||
|
||||
// LDAPConfig is the LDAP connection the idp already uses for its backend.
|
||||
type LDAPConfig struct {
|
||||
URI string
|
||||
BindDN string
|
||||
BindPassword string
|
||||
BaseDN string
|
||||
// Scope is sub, one or base. Empty means sub.
|
||||
Scope string
|
||||
// Filter selects user entries, e.g. "(objectclass=inetOrgPerson)".
|
||||
Filter string
|
||||
// UUIDAttribute holds the oCIS user ID (ownCloudUUID by default).
|
||||
UUIDAttribute string
|
||||
// CACert is a PEM file used to verify the server certificate.
|
||||
CACert string
|
||||
Insecure bool
|
||||
}
|
||||
|
||||
// LDAPIdentities looks up linked external identities directly in LDAP,
|
||||
// because the Graph API cannot filter users by identities.
|
||||
type LDAPIdentities struct {
|
||||
cfg LDAPConfig
|
||||
scope int
|
||||
filter string
|
||||
tls *tls.Config
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
// NewLDAPIdentities returns an LDAPIdentities for cfg.
|
||||
func NewLDAPIdentities(cfg LDAPConfig) (*LDAPIdentities, error) {
|
||||
if cfg.URI == "" || cfg.BaseDN == "" || cfg.UUIDAttribute == "" {
|
||||
return nil, errors.New("ldap uri, base dn and uuid attribute are required")
|
||||
}
|
||||
l := &LDAPIdentities{cfg: cfg, filter: cfg.Filter, timeout: 10 * time.Second}
|
||||
if l.filter == "" {
|
||||
l.filter = "(objectClass=inetOrgPerson)"
|
||||
}
|
||||
switch cfg.Scope {
|
||||
case "", "sub":
|
||||
l.scope = ldap.ScopeWholeSubtree
|
||||
case "one":
|
||||
l.scope = ldap.ScopeSingleLevel
|
||||
case "base":
|
||||
l.scope = ldap.ScopeBaseObject
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown ldap scope %q", cfg.Scope)
|
||||
}
|
||||
|
||||
l.tls = &tls.Config{MinVersion: tls.VersionTLS12}
|
||||
switch {
|
||||
case cfg.Insecure:
|
||||
l.tls.InsecureSkipVerify = true //nolint:gosec // follows IDP_INSECURE like the lico ldap backend
|
||||
case cfg.CACert != "":
|
||||
pem, err := os.ReadFile(cfg.CACert)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read ldap ca certificate: %w", err)
|
||||
}
|
||||
pool, err := x509.SystemCertPool()
|
||||
if err != nil || pool == nil {
|
||||
pool = x509.NewCertPool()
|
||||
}
|
||||
if !pool.AppendCertsFromPEM(pem) {
|
||||
return nil, fmt.Errorf("no certificate found in %s", cfg.CACert)
|
||||
}
|
||||
l.tls.RootCAs = pool
|
||||
}
|
||||
return l, nil
|
||||
}
|
||||
|
||||
// UserIDsByIdentity implements IdentityIndex.
|
||||
func (l *LDAPIdentities) UserIDsByIdentity(_ context.Context, issuer, id string) ([]string, error) {
|
||||
if id == "" {
|
||||
return nil, nil
|
||||
}
|
||||
// A substring filter finds the candidates regardless of the whitespace
|
||||
// around the "$" separators; the exact match is checked below.
|
||||
filter := fmt.Sprintf("(&%s(%s=*%s*))", l.filter, identitiesAttribute, ldap.EscapeFilter(id))
|
||||
entries, err := l.search(filter, []string{l.cfg.UUIDAttribute, identitiesAttribute})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var ids []string
|
||||
for _, e := range entries {
|
||||
if !hasIdentity(e.GetEqualFoldAttributeValues(identitiesAttribute), issuer, id) {
|
||||
continue
|
||||
}
|
||||
if uid := e.GetEqualFoldAttributeValue(l.cfg.UUIDAttribute); uid != "" {
|
||||
ids = append(ids, uid)
|
||||
}
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// HasIssuer reports whether the user with the oCIS user ID userID has an
|
||||
// identity from issuer.
|
||||
func (l *LDAPIdentities) HasIssuer(_ context.Context, userID, issuer string) (bool, error) {
|
||||
if userID == "" {
|
||||
return false, nil
|
||||
}
|
||||
filter := fmt.Sprintf("(&%s(%s=%s))", l.filter, l.cfg.UUIDAttribute, ldap.EscapeFilter(userID))
|
||||
entries, err := l.search(filter, []string{identitiesAttribute})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if len(entries) != 1 {
|
||||
return false, nil
|
||||
}
|
||||
for _, v := range entries[0].GetEqualFoldAttributeValues(identitiesAttribute) {
|
||||
if iss, aid, ok := parseIdentity(v); ok && iss == issuer && aid != "" {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (l *LDAPIdentities) search(filter string, attrs []string) ([]*ldap.Entry, error) {
|
||||
conn, err := ldap.DialURL(l.cfg.URI, ldap.DialWithTLSDialer(l.tls, &net.Dialer{Timeout: l.timeout}))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ldap connect: %w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
conn.SetTimeout(l.timeout)
|
||||
if l.cfg.BindDN != "" {
|
||||
if err := conn.Bind(l.cfg.BindDN, l.cfg.BindPassword); err != nil {
|
||||
return nil, fmt.Errorf("ldap bind: %w", err)
|
||||
}
|
||||
}
|
||||
req := ldap.NewSearchRequest(
|
||||
l.cfg.BaseDN, l.scope, ldap.NeverDerefAliases, 0, int(l.timeout/time.Second), false,
|
||||
filter, attrs, nil,
|
||||
)
|
||||
res, err := conn.Search(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ldap search: %w", err)
|
||||
}
|
||||
return res.Entries, nil
|
||||
}
|
||||
|
||||
func hasIdentity(values []string, issuer, id string) bool {
|
||||
for _, v := range values {
|
||||
if iss, aid, ok := parseIdentity(v); ok && iss == issuer && aid == id {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// parseIdentity splits an oCExternalIdentity value like the graph service.
|
||||
func parseIdentity(v string) (issuer, id string, ok bool) {
|
||||
parts := strings.SplitN(v, "$", 3)
|
||||
if len(parts) != 3 {
|
||||
return "", "", false
|
||||
}
|
||||
return strings.TrimSpace(parts[1]), strings.TrimSpace(parts[2]), true
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
const (
|
||||
modeLink = "link"
|
||||
|
||||
// LinkReturnPath is the web UI page the link flow returns to.
|
||||
LinkReturnPath = "/account"
|
||||
// LinkResultParam carries the result of the link flow: LinkResultOK or
|
||||
// one of the ErrCode values.
|
||||
LinkResultParam = "discord_link"
|
||||
// LinkResultOK means the account was linked.
|
||||
LinkResultOK = "linked"
|
||||
)
|
||||
|
||||
// UserAuthenticator returns the oCIS user ID of a signed in user.
|
||||
type UserAuthenticator interface {
|
||||
// AuthenticateUser returns the user ID, or the HTTP status to answer with.
|
||||
AuthenticateUser(r *http.Request) (string, int, error)
|
||||
}
|
||||
|
||||
// LinkStatus is returned by GET /oauth2/discord/account/link.
|
||||
type LinkStatus struct {
|
||||
// Enabled reports whether Discord login is configured.
|
||||
Enabled bool `json:"enabled"`
|
||||
// Linked reports whether the signed in account is linked to Discord.
|
||||
Linked bool `json:"linked"`
|
||||
}
|
||||
|
||||
// getLink returns the link status of the signed in user.
|
||||
func (h *Handler) getLink(w http.ResponseWriter, r *http.Request) {
|
||||
userID, status, err := h.opt.Users.AuthenticateUser(r)
|
||||
if err != nil {
|
||||
writeJSONError(w, status, "accessDenied", "", http.StatusText(status))
|
||||
return
|
||||
}
|
||||
if !h.opt.Store.Get().Ready() {
|
||||
writeJSON(w, http.StatusOK, LinkStatus{})
|
||||
return
|
||||
}
|
||||
linked, err := h.opt.Provisioner.Linked(r.Context(), userID)
|
||||
if err != nil {
|
||||
h.opt.Logger.Error().Err(err).Str("user_id", userID).Msg("discord: could not load link status")
|
||||
writeJSONError(w, http.StatusInternalServerError, "generalException", "", "could not load the discord link status")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, LinkStatus{Enabled: true, Linked: linked})
|
||||
}
|
||||
|
||||
// startLink starts the Discord authorization for linking the signed in
|
||||
// account. It sets the state cookie and returns the URL the browser has to
|
||||
// open, because a browser navigation cannot carry the bearer token.
|
||||
func (h *Handler) startLink(w http.ResponseWriter, r *http.Request) {
|
||||
userID, status, err := h.opt.Users.AuthenticateUser(r)
|
||||
if err != nil {
|
||||
writeJSONError(w, status, "accessDenied", "", http.StatusText(status))
|
||||
return
|
||||
}
|
||||
if !h.opt.Store.Get().Ready() {
|
||||
writeJSONError(w, http.StatusNotFound, "notFound", "", "discord login is disabled")
|
||||
return
|
||||
}
|
||||
linked, err := h.opt.Provisioner.Linked(r.Context(), userID)
|
||||
if err != nil {
|
||||
h.opt.Logger.Error().Err(err).Str("user_id", userID).Msg("discord: could not load link status")
|
||||
writeJSONError(w, http.StatusInternalServerError, "generalException", "", "could not load the discord link status")
|
||||
return
|
||||
}
|
||||
if linked {
|
||||
writeJSONError(w, http.StatusConflict, "conflict", "", "the account is already linked to discord")
|
||||
return
|
||||
}
|
||||
target, err := h.beginAuthorization(w, stateData{Mode: modeLink, UserID: userID})
|
||||
if err != nil {
|
||||
h.opt.Logger.Error().Err(err).Msg("discord: could not start authorization")
|
||||
writeJSONError(w, http.StatusInternalServerError, "generalException", "", "could not start the discord authorization")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"url": target})
|
||||
}
|
||||
|
||||
// finishLink links du to the account that started the link flow. It does
|
||||
// not issue a logon cookie: the user is already signed in.
|
||||
func (h *Handler) finishLink(w http.ResponseWriter, r *http.Request, userID string, du *User) {
|
||||
logger := h.opt.Logger.With().Str("component", "discord").Str("user_id", userID).Str("discord_id", du.ID).Logger()
|
||||
err := h.opt.Provisioner.Link(r.Context(), userID, du)
|
||||
switch {
|
||||
case errors.Is(err, ErrIdentityConflict):
|
||||
logger.Info().Msg("discord link refused: linked to another account")
|
||||
h.linkResult(w, r, ErrCodeLinkConflict)
|
||||
case err != nil:
|
||||
logger.Error().Err(err).Msg("discord link failed")
|
||||
h.linkResult(w, r, ErrCodeProvision)
|
||||
default:
|
||||
logger.Info().Msg("linked discord to account")
|
||||
h.linkResult(w, r, LinkResultOK)
|
||||
}
|
||||
}
|
||||
|
||||
// linkResult returns to the account page with the result of the link flow.
|
||||
func (h *Handler) linkResult(w http.ResponseWriter, r *http.Request, result string) {
|
||||
h.opt.Render.Continue(w, r, LinkReturnPath+"?"+url.Values{LinkResultParam: {result}}.Encode())
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type fakeUsers struct {
|
||||
id string
|
||||
status int
|
||||
}
|
||||
|
||||
func (f *fakeUsers) AuthenticateUser(*http.Request) (string, int, error) {
|
||||
if f.status != http.StatusOK {
|
||||
return "", f.status, errors.New("denied")
|
||||
}
|
||||
return f.id, http.StatusOK, nil
|
||||
}
|
||||
|
||||
func (f *fakeProvisioner) Link(_ context.Context, userID string, u *User) error {
|
||||
if f.linkErr != nil {
|
||||
return f.linkErr
|
||||
}
|
||||
f.linkedID, f.linkedUser = userID, u
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeProvisioner) Linked(context.Context, string) (bool, error) {
|
||||
return f.isLinked, f.linkedErr
|
||||
}
|
||||
|
||||
// startLink starts the link flow and returns the state sent to Discord and
|
||||
// the state cookie.
|
||||
func (h *harness) startLink() (string, *http.Cookie) {
|
||||
h.t.Helper()
|
||||
rec := h.do(http.MethodPost, "/oauth2/discord/account/link", nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
h.t.Fatalf("start link status = %d body = %s", rec.Code, rec.Body)
|
||||
}
|
||||
var body struct {
|
||||
URL string `json:"url"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
h.t.Fatal(err)
|
||||
}
|
||||
loc, err := url.Parse(body.URL)
|
||||
if err != nil {
|
||||
h.t.Fatal(err)
|
||||
}
|
||||
state := loc.Query().Get("state")
|
||||
c := findCookie(rec, stateCookieName)
|
||||
if state == "" || c == nil {
|
||||
h.t.Fatalf("start link did not set state (url=%q cookie=%v)", body.URL, c)
|
||||
}
|
||||
return state, c
|
||||
}
|
||||
|
||||
func linkResultOf(t *testing.T, target string) string {
|
||||
t.Helper()
|
||||
u, err := url.Parse(target)
|
||||
if err != nil || u.Path != LinkReturnPath {
|
||||
t.Fatalf("link flow returned to %q", target)
|
||||
}
|
||||
return u.Query().Get(LinkResultParam)
|
||||
}
|
||||
|
||||
func TestLinkFlowLinksSignedInAccount(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
state, c := h.startLink()
|
||||
rec := h.callback(cbQuery(testCode, state), c)
|
||||
if rec.Code != http.StatusOK || linkResultOf(t, h.render.target) != LinkResultOK {
|
||||
t.Fatalf("status = %d target = %q", rec.Code, h.render.target)
|
||||
}
|
||||
if h.prov.linkedID != h.users.id || h.prov.linkedUser == nil || h.prov.linkedUser.ID != h.fd.user.ID {
|
||||
t.Errorf("linked %q to %+v", h.prov.linkedID, h.prov.linkedUser)
|
||||
}
|
||||
if h.sess.userID != "" || h.prov.calls != 0 {
|
||||
t.Error("the link flow must not log on or look up another account")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLinkFlowErrors(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
setup func(h *harness)
|
||||
query func(state string) string
|
||||
want string
|
||||
}{
|
||||
{"linked to another account", func(h *harness) { h.prov.linkErr = ErrIdentityConflict }, nil, ErrCodeLinkConflict},
|
||||
{"link failure", func(h *harness) { h.prov.linkErr = errors.New("graph down") }, nil, ErrCodeProvision},
|
||||
{"not member", func(h *harness) { h.fd.guilds = []Guild{{ID: "100000000000000001"}} }, nil, ErrCodeNotMember},
|
||||
{"cancelled", nil, func(s string) string {
|
||||
return url.Values{"state": {s}, "error": {"access_denied"}}.Encode()
|
||||
}, ErrCodeCancelled},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
if tt.setup != nil {
|
||||
tt.setup(h)
|
||||
}
|
||||
state, c := h.startLink()
|
||||
q := cbQuery(testCode, state)
|
||||
if tt.query != nil {
|
||||
q = tt.query(state)
|
||||
}
|
||||
h.callback(q, c)
|
||||
if got := linkResultOf(t, h.render.target); got != tt.want {
|
||||
t.Errorf("result = %q, want %q", got, tt.want)
|
||||
}
|
||||
if h.prov.linkedID != "" || h.sess.userID != "" {
|
||||
t.Error("account linked or logged on despite the error")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartLinkRequiresAuthentication(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.users.status = http.StatusUnauthorized
|
||||
for _, method := range []string{http.MethodGet, http.MethodPost} {
|
||||
rec := h.do(method, "/oauth2/discord/account/link", nil)
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("%s status = %d, want 401", method, rec.Code)
|
||||
}
|
||||
if findCookie(rec, stateCookieName) != nil {
|
||||
t.Errorf("%s set a state cookie without authentication", method)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartLinkRefused(t *testing.T) {
|
||||
t.Run("already linked", func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.prov.isLinked = true
|
||||
if rec := h.do(http.MethodPost, "/oauth2/discord/account/link", nil); rec.Code != http.StatusConflict {
|
||||
t.Fatalf("status = %d, want 409", rec.Code)
|
||||
}
|
||||
})
|
||||
t.Run("disabled", func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
if err := h.store.Save(Settings{ClientID: testClientID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rec := h.do(http.MethodPost, "/oauth2/discord/account/link", nil); rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d, want 404", rec.Code)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestGetLinkStatus(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.prov.isLinked = true
|
||||
var s LinkStatus
|
||||
rec := h.do(http.MethodGet, "/oauth2/discord/account/link", nil)
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &s); err != nil || rec.Code != http.StatusOK || !s.Enabled || !s.Linked {
|
||||
t.Fatalf("status = %d body = %s", rec.Code, rec.Body)
|
||||
}
|
||||
if err := h.store.Save(Settings{ClientID: testClientID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s = LinkStatus{}
|
||||
rec = h.do(http.MethodGet, "/oauth2/discord/account/link", nil)
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &s); err != nil || s.Enabled || s.Linked {
|
||||
t.Fatalf("disabled status body = %s", rec.Body)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
)
|
||||
|
||||
const maxLogonBody = 64 << 10
|
||||
|
||||
// GuardLogon wraps the lico logon endpoint. lico cannot tell a pending
|
||||
// (disabled) account from a wrong password, so when the logon fails for a
|
||||
// username that waits for approval, the response is replaced by
|
||||
// {"success":false,"error":"registration_pending"} with status 403.
|
||||
// All other requests pass through unchanged.
|
||||
func (h *Handler) GuardLogon(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, maxLogonBody))
|
||||
if err != nil {
|
||||
http.Error(w, "bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
r.Body = io.NopCloser(bytes.NewReader(body))
|
||||
|
||||
var req struct {
|
||||
State string `json:"state"`
|
||||
Params []string `json:"params"`
|
||||
}
|
||||
if json.Unmarshal(body, &req) != nil || len(req.Params) == 0 || !h.opt.Pending.IsPendingUsername(req.Params[0]) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
next.ServeHTTP(rec, r)
|
||||
var res struct {
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
if rec.Code == http.StatusOK && json.Unmarshal(rec.Body.Bytes(), &res) == nil && res.Success {
|
||||
// The account was enabled meanwhile: keep the lico response.
|
||||
for k, v := range rec.Header() {
|
||||
w.Header()[k] = v
|
||||
}
|
||||
w.WriteHeader(rec.Code)
|
||||
_, _ = w.Write(rec.Body.Bytes())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusForbidden, map[string]any{
|
||||
"success": false,
|
||||
"state": req.State,
|
||||
"error": ErrCodePendingApproval,
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func fakeLico(success bool, calls *int) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
*calls++
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
if !strings.Contains(string(b), "params") {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if success {
|
||||
w.Header().Set("X-Lico", "1")
|
||||
_, _ = w.Write([]byte(`{"success":true}`))
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
}
|
||||
|
||||
func postLogon(h http.Handler, user string) *httptest.ResponseRecorder {
|
||||
body := `{"state":"s1","params":["` + user + `","pw","1"]}`
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/signin/v1/identifier/_/logon", strings.NewReader(body)))
|
||||
return rec
|
||||
}
|
||||
|
||||
func TestGuardLogonPendingUser(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
_ = h.pending.Add(PendingUser{UserID: "u1", Username: "alice", Source: SourceWeb})
|
||||
calls := 0
|
||||
rec := postLogon(h.handler.GuardLogon(fakeLico(false, &calls)), "Alice")
|
||||
var res map[string]any
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
if rec.Code != http.StatusForbidden || res["error"] != ErrCodePendingApproval || res["success"] != false || calls != 1 {
|
||||
t.Fatalf("status = %d body = %s calls = %d", rec.Code, rec.Body, calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuardLogonPassesOtherUsers(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
calls := 0
|
||||
if rec := postLogon(h.handler.GuardLogon(fakeLico(false, &calls)), "bob"); rec.Code != http.StatusNoContent || calls != 1 {
|
||||
t.Fatalf("failed logon must stay a lico failure: %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuardLogonApprovedMeanwhile(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
_ = h.pending.Add(PendingUser{UserID: "u1", Username: "alice", Source: SourceWeb})
|
||||
calls := 0
|
||||
rec := postLogon(h.handler.GuardLogon(fakeLico(true, &calls)), "alice")
|
||||
if rec.Code != http.StatusOK || rec.Header().Get("X-Lico") != "1" || !strings.Contains(rec.Body.String(), `"success":true`) {
|
||||
t.Fatalf("status = %d body = %s", rec.Code, rec.Body)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Registration sources stored with a pending account.
|
||||
const (
|
||||
SourceWeb = "web"
|
||||
SourceDiscord = "discord"
|
||||
)
|
||||
|
||||
// PendingUser is an account that was created disabled and waits for an
|
||||
// administrator's approval.
|
||||
type PendingUser struct {
|
||||
UserID string `json:"user_id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name,omitempty"`
|
||||
Mail string `json:"mail,omitempty"`
|
||||
Source string `json:"source"`
|
||||
RequestedAt time.Time `json:"requested_at"`
|
||||
}
|
||||
|
||||
// PendingStore persists the pending accounts as a JSON file (mode 0600).
|
||||
type PendingStore struct {
|
||||
path string
|
||||
mu sync.RWMutex
|
||||
cur map[string]PendingUser
|
||||
}
|
||||
|
||||
// NewPendingStore loads the pending accounts from path. A missing file means
|
||||
// no pending accounts.
|
||||
func NewPendingStore(path string) (*PendingStore, error) {
|
||||
s := &PendingStore{path: path, cur: map[string]PendingUser{}}
|
||||
if err := readJSONFile(path, &s.cur); err != nil {
|
||||
return nil, fmt.Errorf("load pending accounts: %w", err)
|
||||
}
|
||||
if s.cur == nil {
|
||||
s.cur = map[string]PendingUser{}
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// IsPending reports whether userID waits for approval.
|
||||
func (s *PendingStore) IsPending(userID string) bool {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
_, ok := s.cur[userID]
|
||||
return ok
|
||||
}
|
||||
|
||||
// IsPendingUsername reports whether an account with the username waits for
|
||||
// approval. Usernames are compared case-insensitively like LDAP does.
|
||||
func (s *PendingStore) IsPendingUsername(name string) bool {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
return false
|
||||
}
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
for _, p := range s.cur {
|
||||
if strings.EqualFold(p.Username, name) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Get returns the pending account userID.
|
||||
func (s *PendingStore) Get(userID string) (PendingUser, bool) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
p, ok := s.cur[userID]
|
||||
return p, ok
|
||||
}
|
||||
|
||||
// List returns the pending accounts, oldest request first.
|
||||
func (s *PendingStore) List() []PendingUser {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
out := make([]PendingUser, 0, len(s.cur))
|
||||
for _, p := range s.cur {
|
||||
out = append(out, p)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
if out[i].RequestedAt.Equal(out[j].RequestedAt) {
|
||||
return out[i].UserID < out[j].UserID
|
||||
}
|
||||
return out[i].RequestedAt.Before(out[j].RequestedAt)
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// Add records p as pending.
|
||||
func (s *PendingStore) Add(p PendingUser) error {
|
||||
if p.UserID == "" {
|
||||
return fmt.Errorf("pending account without user id")
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
next := s.copyLocked()
|
||||
next[p.UserID] = p
|
||||
return s.saveLocked(next)
|
||||
}
|
||||
|
||||
// Remove forgets userID. Removing an unknown ID is not an error.
|
||||
func (s *PendingStore) Remove(userID string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if _, ok := s.cur[userID]; !ok {
|
||||
return nil
|
||||
}
|
||||
next := s.copyLocked()
|
||||
delete(next, userID)
|
||||
return s.saveLocked(next)
|
||||
}
|
||||
|
||||
func (s *PendingStore) copyLocked() map[string]PendingUser {
|
||||
next := make(map[string]PendingUser, len(s.cur)+1)
|
||||
for k, v := range s.cur {
|
||||
next[k] = v
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
func (s *PendingStore) saveLocked(next map[string]PendingUser) error {
|
||||
if err := writeJSONFile(s.path, next); err != nil {
|
||||
return fmt.Errorf("save pending accounts: %w", err)
|
||||
}
|
||||
s.cur = next
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestPendingStore(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "pending.json")
|
||||
s, err := NewPendingStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(s.List()) != 0 || s.IsPending("a") {
|
||||
t.Fatal("new store must be empty")
|
||||
}
|
||||
t0 := time.Unix(1700000000, 0).UTC()
|
||||
if err := s.Add(PendingUser{UserID: "b", Username: "bob", Source: SourceWeb, RequestedAt: t0.Add(time.Minute)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Add(PendingUser{UserID: "a", Username: "alice", Source: SourceDiscord, RequestedAt: t0}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Add(PendingUser{}); err == nil {
|
||||
t.Error("an entry without user id must be refused")
|
||||
}
|
||||
|
||||
reloaded, err := NewPendingStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l := reloaded.List()
|
||||
if len(l) != 2 || l[0].UserID != "a" || l[1].UserID != "b" || l[0].Source != SourceDiscord {
|
||||
t.Fatalf("list = %+v", l)
|
||||
}
|
||||
|
||||
if err := reloaded.Remove("a"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := reloaded.Remove("unknown"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if reloaded.IsPending("a") || !reloaded.IsPending("b") {
|
||||
t.Fatal("remove did not work")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
libregraph "github.com/owncloud/libre-graph-api-go"
|
||||
)
|
||||
|
||||
// IdentityIssuer is stored as identities[].issuer for linked Discord users.
|
||||
const IdentityIssuer = "https://discord.com"
|
||||
|
||||
var (
|
||||
// ErrIdentityConflict means the matching oCIS account is already linked
|
||||
// to a different Discord user.
|
||||
ErrIdentityConflict = errors.New("account is already linked to another discord user")
|
||||
// ErrUsernameInvalid means the chosen username does not match usernamePattern.
|
||||
ErrUsernameInvalid = errors.New("invalid username")
|
||||
// ErrUsernameTaken means an account with the chosen username exists.
|
||||
ErrUsernameTaken = errors.New("username is already taken")
|
||||
)
|
||||
|
||||
// UserPatch lists the attributes the provisioner updates. Nil or empty
|
||||
// fields are left unchanged.
|
||||
type UserPatch struct {
|
||||
AccountEnabled *bool
|
||||
DisplayName *string
|
||||
Mail *string
|
||||
Identities []libregraph.ObjectIdentity
|
||||
}
|
||||
|
||||
// Directory is the subset of the LibreGraph users API the provisioner needs.
|
||||
type Directory interface {
|
||||
// GetUserByName returns nil, nil when the user does not exist.
|
||||
GetUserByName(ctx context.Context, name string) (*libregraph.User, error)
|
||||
// FindUsersByMail returns candidates; callers must match exactly.
|
||||
FindUsersByMail(ctx context.Context, mail string) ([]libregraph.User, error)
|
||||
CreateUser(ctx context.Context, u libregraph.User) (*libregraph.User, error)
|
||||
UpdateUser(ctx context.Context, id string, p UserPatch) error
|
||||
// DeleteUser removes the account. A missing account is not an error.
|
||||
DeleteUser(ctx context.Context, id string) error
|
||||
}
|
||||
|
||||
// IdentityIndex finds accounts by a linked external identity.
|
||||
type IdentityIndex interface {
|
||||
// UserIDsByIdentity returns the oCIS user IDs linked to issuer and id.
|
||||
UserIDsByIdentity(ctx context.Context, issuer, id string) ([]string, error)
|
||||
}
|
||||
|
||||
// usernamePattern is a subset of the graph "default" username rule that is
|
||||
// also safe in LDAP DNs and URLs.
|
||||
var usernamePattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9._-]{2,31}$`)
|
||||
|
||||
// ValidUsername reports whether name may be chosen as a username.
|
||||
func ValidUsername(name string) bool { return usernamePattern.MatchString(name) }
|
||||
|
||||
// SuggestUsername returns the Discord username when it is a valid username,
|
||||
// otherwise "".
|
||||
func SuggestUsername(du *User) string {
|
||||
if du == nil {
|
||||
return ""
|
||||
}
|
||||
if n := strings.ToLower(strings.TrimSpace(du.Username)); ValidUsername(n) {
|
||||
return n
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// GraphProvisioner implements Provisioner on top of a Directory and an
|
||||
// IdentityIndex.
|
||||
type GraphProvisioner struct {
|
||||
Dir Directory
|
||||
Index IdentityIndex
|
||||
}
|
||||
|
||||
// Lookup implements Provisioner.
|
||||
//
|
||||
// Lookup order:
|
||||
// 1. the account linked to the Discord ID (identities)
|
||||
// 2. an existing account with the same email, only when Discord reports the
|
||||
// email as verified (an unverified email would allow account takeover);
|
||||
// the Discord identity is linked to it
|
||||
// 3. otherwise "" is returned and the user has to choose a username
|
||||
func (p GraphProvisioner) Lookup(ctx context.Context, du *User) (string, error) {
|
||||
if err := checkDiscordUser(du); err != nil {
|
||||
return "", err
|
||||
}
|
||||
ids, err := p.Index.UserIDsByIdentity(ctx, IdentityIssuer, du.ID)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("lookup linked account: %w", err)
|
||||
}
|
||||
switch len(ids) {
|
||||
case 0:
|
||||
case 1:
|
||||
return ids[0], nil
|
||||
default:
|
||||
return "", fmt.Errorf("%d accounts are linked to discord user %s", len(ids), du.ID)
|
||||
}
|
||||
|
||||
mail := du.VerifiedEmail()
|
||||
if mail == "" {
|
||||
return "", nil
|
||||
}
|
||||
candidates, err := p.Dir.FindUsersByMail(ctx, mail)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("lookup user by email: %w", err)
|
||||
}
|
||||
var matches []libregraph.User
|
||||
for _, c := range candidates {
|
||||
if strings.EqualFold(strings.TrimSpace(c.GetMail()), mail) {
|
||||
matches = append(matches, c)
|
||||
}
|
||||
}
|
||||
switch len(matches) {
|
||||
case 0:
|
||||
return "", nil
|
||||
case 1:
|
||||
m := matches[0]
|
||||
if linked, ok := discordIdentity(&m); ok && linked != du.ID {
|
||||
return "", ErrIdentityConflict
|
||||
}
|
||||
// Existing local account: only link it, keep its profile.
|
||||
return p.link(ctx, &m, du)
|
||||
default:
|
||||
return "", fmt.Errorf("%d accounts share the email address, refusing to link", len(matches))
|
||||
}
|
||||
}
|
||||
|
||||
// Create implements Provisioner. It creates the account with the username
|
||||
// the user chose and links the Discord identity.
|
||||
func (p GraphProvisioner) Create(ctx context.Context, du *User, username string, enabled bool) (string, error) {
|
||||
if err := checkDiscordUser(du); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !ValidUsername(username) {
|
||||
return "", ErrUsernameInvalid
|
||||
}
|
||||
existing, err := p.Dir.GetUserByName(ctx, username)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("lookup user %s: %w", username, err)
|
||||
}
|
||||
if existing != nil {
|
||||
return "", ErrUsernameTaken
|
||||
}
|
||||
|
||||
nu := libregraph.User{}
|
||||
nu.SetOnPremisesSamAccountName(username)
|
||||
nu.SetDisplayName(du.DisplayName())
|
||||
if mail := du.VerifiedEmail(); mail != "" {
|
||||
nu.SetMail(mail)
|
||||
}
|
||||
nu.SetAccountEnabled(enabled)
|
||||
nu.SetIdentities([]libregraph.ObjectIdentity{newIdentity(du.ID)})
|
||||
|
||||
created, err := p.Dir.CreateUser(ctx, nu)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("create user %s: %w", username, err)
|
||||
}
|
||||
if created == nil || created.GetId() == "" {
|
||||
return "", errors.New("created user has no id")
|
||||
}
|
||||
return created.GetId(), nil
|
||||
}
|
||||
|
||||
// Link implements Provisioner. It links du to the existing account userID.
|
||||
func (p GraphProvisioner) Link(ctx context.Context, userID string, du *User) error {
|
||||
if err := checkDiscordUser(du); err != nil {
|
||||
return err
|
||||
}
|
||||
if userID == "" {
|
||||
return errors.New("empty user id")
|
||||
}
|
||||
ids, err := p.Index.UserIDsByIdentity(ctx, IdentityIssuer, du.ID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("lookup linked account: %w", err)
|
||||
}
|
||||
for _, id := range ids {
|
||||
if id != userID {
|
||||
return ErrIdentityConflict
|
||||
}
|
||||
}
|
||||
u, err := p.Dir.GetUserByName(ctx, userID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("lookup user %s: %w", userID, err)
|
||||
}
|
||||
if u == nil {
|
||||
return fmt.Errorf("user %s not found", userID)
|
||||
}
|
||||
if linked, ok := discordIdentity(u); ok {
|
||||
if linked != du.ID {
|
||||
return ErrIdentityConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
_, err = p.link(ctx, u, du)
|
||||
return err
|
||||
}
|
||||
|
||||
// Linked implements Provisioner.
|
||||
func (p GraphProvisioner) Linked(ctx context.Context, userID string) (bool, error) {
|
||||
u, err := p.Dir.GetUserByName(ctx, userID)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("lookup user %s: %w", userID, err)
|
||||
}
|
||||
if u == nil {
|
||||
return false, nil
|
||||
}
|
||||
_, ok := discordIdentity(u)
|
||||
return ok, nil
|
||||
}
|
||||
|
||||
// link adds the Discord identity to u unless it is already linked.
|
||||
func (p GraphProvisioner) link(ctx context.Context, u *libregraph.User, du *User) (string, error) {
|
||||
id := u.GetId()
|
||||
if id == "" {
|
||||
return "", errors.New("user has no id")
|
||||
}
|
||||
if _, ok := discordIdentity(u); ok {
|
||||
return id, nil
|
||||
}
|
||||
identities := append(append([]libregraph.ObjectIdentity{}, u.GetIdentities()...), newIdentity(du.ID))
|
||||
if err := p.Dir.UpdateUser(ctx, id, UserPatch{Identities: identities}); err != nil {
|
||||
return "", fmt.Errorf("update user %s: %w", id, err)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// CreateWebUser implements WebAccounts. Username and email must be unused.
|
||||
func (p GraphProvisioner) CreateWebUser(ctx context.Context, wu WebUser, enabled bool) (string, error) {
|
||||
if !ValidUsername(wu.Username) {
|
||||
return "", ErrUsernameInvalid
|
||||
}
|
||||
existing, err := p.Dir.GetUserByName(ctx, wu.Username)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("lookup user %s: %w", wu.Username, err)
|
||||
}
|
||||
if existing != nil {
|
||||
return "", ErrUsernameTaken
|
||||
}
|
||||
candidates, err := p.Dir.FindUsersByMail(ctx, wu.Mail)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("lookup user by email: %w", err)
|
||||
}
|
||||
for _, c := range candidates {
|
||||
if strings.EqualFold(strings.TrimSpace(c.GetMail()), wu.Mail) {
|
||||
return "", ErrMailTaken
|
||||
}
|
||||
}
|
||||
|
||||
nu := libregraph.User{}
|
||||
nu.SetOnPremisesSamAccountName(wu.Username)
|
||||
nu.SetDisplayName(wu.Username)
|
||||
nu.SetMail(wu.Mail)
|
||||
nu.SetAccountEnabled(enabled)
|
||||
pp := libregraph.NewPasswordProfile()
|
||||
pp.SetPassword(wu.Password)
|
||||
nu.SetPasswordProfile(*pp)
|
||||
|
||||
created, err := p.Dir.CreateUser(ctx, nu)
|
||||
if err != nil {
|
||||
var se *GraphStatusError
|
||||
if errors.As(err, &se) && se.Status == 400 && strings.Contains(strings.ToLower(se.Body), "password") {
|
||||
return "", fmt.Errorf("%w: %s", ErrPasswordRejected, se.Body)
|
||||
}
|
||||
return "", fmt.Errorf("create user %s: %w", wu.Username, err)
|
||||
}
|
||||
if created == nil || created.GetId() == "" {
|
||||
return "", errors.New("created user has no id")
|
||||
}
|
||||
return created.GetId(), nil
|
||||
}
|
||||
|
||||
// Approve implements Accounts: it enables the pending account.
|
||||
func (p GraphProvisioner) Approve(ctx context.Context, userID string) error {
|
||||
enabled := true
|
||||
return p.Dir.UpdateUser(ctx, userID, UserPatch{AccountEnabled: &enabled})
|
||||
}
|
||||
|
||||
// Reject implements Accounts: it deletes the pending account.
|
||||
func (p GraphProvisioner) Reject(ctx context.Context, userID string) error {
|
||||
return p.Dir.DeleteUser(ctx, userID)
|
||||
}
|
||||
|
||||
func checkDiscordUser(du *User) error {
|
||||
if du == nil || !snowflake.MatchString(du.ID) {
|
||||
return errors.New("invalid discord user id")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func newIdentity(discordID string) libregraph.ObjectIdentity {
|
||||
oi := libregraph.NewObjectIdentity()
|
||||
oi.SetIssuer(IdentityIssuer)
|
||||
oi.SetIssuerAssignedId(discordID)
|
||||
return *oi
|
||||
}
|
||||
|
||||
// discordIdentity returns the linked Discord ID of u, if any.
|
||||
func discordIdentity(u *libregraph.User) (string, bool) {
|
||||
for _, oi := range u.GetIdentities() {
|
||||
if oi.GetIssuer() == IdentityIssuer && oi.GetIssuerAssignedId() != "" {
|
||||
return oi.GetIssuerAssignedId(), true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLinkAddsIdentityToExistingAccount(t *testing.T) {
|
||||
dir := newFakeDirectory(graphUser("uid-1", "bob", "bob@example.com", "Bob", ""))
|
||||
if err := prov(dir).Link(context.Background(), "uid-1", discordUser()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, ok := dir.updates["uid-1"]
|
||||
if !ok || len(p.Identities) != 1 || p.Identities[0].GetIssuerAssignedId() != testDiscordID {
|
||||
t.Fatalf("unexpected patch %+v", p)
|
||||
}
|
||||
if p.DisplayName != nil || p.Mail != nil {
|
||||
t.Error("the profile of the account must be kept")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLinkConflicts(t *testing.T) {
|
||||
t.Run("discord user linked to another account", func(t *testing.T) {
|
||||
dir := newFakeDirectory(graphUser("uid-1", "bob", "", "Bob", ""))
|
||||
if err := prov(dir, "other-id").Link(context.Background(), "uid-1", discordUser()); !errors.Is(err, ErrIdentityConflict) {
|
||||
t.Fatalf("err = %v, want ErrIdentityConflict", err)
|
||||
}
|
||||
if len(dir.updates) != 0 {
|
||||
t.Error("account was modified")
|
||||
}
|
||||
})
|
||||
t.Run("account linked to another discord user", func(t *testing.T) {
|
||||
dir := newFakeDirectory(graphUser("uid-1", "bob", "", "Bob", "999999999999999999"))
|
||||
if err := prov(dir).Link(context.Background(), "uid-1", discordUser()); !errors.Is(err, ErrIdentityConflict) {
|
||||
t.Fatalf("err = %v, want ErrIdentityConflict", err)
|
||||
}
|
||||
if len(dir.updates) != 0 {
|
||||
t.Error("account was modified")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestLinkAlreadyLinkedToSameUser(t *testing.T) {
|
||||
dir := newFakeDirectory(graphUser("uid-1", "bob", "", "Bob", testDiscordID))
|
||||
if err := prov(dir, "uid-1").Link(context.Background(), "uid-1", discordUser()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(dir.updates) != 0 {
|
||||
t.Error("an existing link must not be patched again")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLinkMissingAccount(t *testing.T) {
|
||||
if err := prov(newFakeDirectory()).Link(context.Background(), "uid-1", discordUser()); err == nil {
|
||||
t.Fatal("expected an error for a missing account")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLinked(t *testing.T) {
|
||||
dir := newFakeDirectory(
|
||||
graphUser("linked", "a", "", "A", testDiscordID),
|
||||
graphUser("plain", "b", "", "B", ""),
|
||||
)
|
||||
for id, want := range map[string]bool{"linked": true, "plain": false, "missing": false} {
|
||||
if got, err := prov(dir).Linked(context.Background(), id); err != nil || got != want {
|
||||
t.Errorf("Linked(%q) = %v, %v; want %v", id, got, err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
libregraph "github.com/owncloud/libre-graph-api-go"
|
||||
)
|
||||
|
||||
const testDiscordID = "111111111111111111"
|
||||
|
||||
// fakeDirectory mimics the LibreGraph users API. FindUsersByMail matches by
|
||||
// substring like the Graph $search does.
|
||||
type fakeDirectory struct {
|
||||
users []libregraph.User
|
||||
created []libregraph.User
|
||||
updates map[string]UserPatch
|
||||
deleted []string
|
||||
mailCalls int
|
||||
createErr error
|
||||
}
|
||||
|
||||
func newFakeDirectory(users ...libregraph.User) *fakeDirectory {
|
||||
return &fakeDirectory{users: users, updates: map[string]UserPatch{}}
|
||||
}
|
||||
|
||||
func (d *fakeDirectory) GetUserByName(_ context.Context, name string) (*libregraph.User, error) {
|
||||
for _, u := range d.users {
|
||||
// The Graph API accepts a user name or ID.
|
||||
if u.GetId() == name || strings.EqualFold(u.GetOnPremisesSamAccountName(), name) {
|
||||
c := u
|
||||
return &c, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (d *fakeDirectory) FindUsersByMail(_ context.Context, mail string) ([]libregraph.User, error) {
|
||||
d.mailCalls++
|
||||
var out []libregraph.User
|
||||
for _, u := range d.users {
|
||||
if strings.Contains(strings.ToLower(u.GetMail()), strings.ToLower(mail)) {
|
||||
out = append(out, u)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (d *fakeDirectory) CreateUser(_ context.Context, u libregraph.User) (*libregraph.User, error) {
|
||||
if d.createErr != nil {
|
||||
return nil, d.createErr
|
||||
}
|
||||
d.created = append(d.created, u)
|
||||
u.SetId("new-user-id")
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
func (d *fakeDirectory) UpdateUser(_ context.Context, id string, p UserPatch) error {
|
||||
d.updates[id] = p
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *fakeDirectory) DeleteUser(_ context.Context, id string) error {
|
||||
d.deleted = append(d.deleted, id)
|
||||
return nil
|
||||
}
|
||||
|
||||
// fakeIndex returns linked user IDs per Discord ID.
|
||||
type fakeIndex struct {
|
||||
linked map[string][]string
|
||||
err error
|
||||
}
|
||||
|
||||
func (f fakeIndex) UserIDsByIdentity(_ context.Context, issuer, id string) ([]string, error) {
|
||||
if issuer != IdentityIssuer {
|
||||
return nil, errors.New("unexpected issuer " + issuer)
|
||||
}
|
||||
return f.linked[id], f.err
|
||||
}
|
||||
|
||||
func graphUser(id, name, mail, display, discordID string) libregraph.User {
|
||||
u := libregraph.User{}
|
||||
u.SetId(id)
|
||||
u.SetOnPremisesSamAccountName(name)
|
||||
u.SetDisplayName(display)
|
||||
if mail != "" {
|
||||
u.SetMail(mail)
|
||||
}
|
||||
if discordID != "" {
|
||||
u.SetIdentities([]libregraph.ObjectIdentity{newIdentity(discordID)})
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
func discordUser() *User {
|
||||
return &User{ID: testDiscordID, Username: "alice", GlobalName: "Alice", Email: "alice@example.com", Verified: true}
|
||||
}
|
||||
|
||||
func prov(dir *fakeDirectory, linked ...string) GraphProvisioner {
|
||||
idx := fakeIndex{linked: map[string][]string{}}
|
||||
if len(linked) > 0 {
|
||||
idx.linked[testDiscordID] = linked
|
||||
}
|
||||
return GraphProvisioner{Dir: dir, Index: idx}
|
||||
}
|
||||
|
||||
func TestLookupLinkedAccount(t *testing.T) {
|
||||
dir := newFakeDirectory()
|
||||
id, err := prov(dir, "linked-id").Lookup(context.Background(), discordUser())
|
||||
if err != nil || id != "linked-id" {
|
||||
t.Fatalf("id = %q err = %v", id, err)
|
||||
}
|
||||
if dir.mailCalls != 0 || len(dir.updates) != 0 || len(dir.created) != 0 {
|
||||
t.Error("a linked account must be used as is")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLookupMultipleLinkedAccounts(t *testing.T) {
|
||||
if _, err := prov(newFakeDirectory(), "a", "b").Lookup(context.Background(), discordUser()); err == nil {
|
||||
t.Fatal("expected an error when several accounts are linked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLookupWithoutAccountCreatesNothing(t *testing.T) {
|
||||
dir := newFakeDirectory()
|
||||
id, err := prov(dir).Lookup(context.Background(), discordUser())
|
||||
if err != nil || id != "" {
|
||||
t.Fatalf("id = %q err = %v", id, err)
|
||||
}
|
||||
if len(dir.created) != 0 || len(dir.updates) != 0 {
|
||||
t.Error("lookup must not create or modify accounts")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLookupUnverifiedEmailIsIgnored(t *testing.T) {
|
||||
dir := newFakeDirectory(graphUser("local-id", "alice", "alice@example.com", "Alice Local", ""))
|
||||
du := discordUser()
|
||||
du.Verified = false
|
||||
id, err := prov(dir).Lookup(context.Background(), du)
|
||||
if err != nil || id != "" || dir.mailCalls != 0 || len(dir.updates) != 0 {
|
||||
t.Fatalf("unverified email must not link accounts (id=%q mailCalls=%d err=%v)", id, dir.mailCalls, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLookupLinksByVerifiedEmail(t *testing.T) {
|
||||
dir := newFakeDirectory(
|
||||
graphUser("local-id", "alice", "Alice@Example.com", "Alice Local", ""),
|
||||
graphUser("other-id", "malice", "xalice@example.com", "Malice", ""),
|
||||
)
|
||||
id, err := prov(dir).Lookup(context.Background(), discordUser())
|
||||
if err != nil || id != "local-id" {
|
||||
t.Fatalf("id = %q err = %v", id, err)
|
||||
}
|
||||
p := dir.updates["local-id"]
|
||||
if p.DisplayName != nil || p.Mail != nil {
|
||||
t.Error("the profile of an existing local account must be kept")
|
||||
}
|
||||
if len(p.Identities) != 1 || p.Identities[0].GetIssuerAssignedId() != testDiscordID {
|
||||
t.Errorf("identity not linked: %+v", p.Identities)
|
||||
}
|
||||
if _, touched := dir.updates["other-id"]; touched {
|
||||
t.Error("substring email match must not be linked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLookupRefusesAmbiguousEmail(t *testing.T) {
|
||||
dir := newFakeDirectory(
|
||||
graphUser("a", "alice1", "alice@example.com", "A", ""),
|
||||
graphUser("b", "alice2", "alice@example.com", "B", ""),
|
||||
)
|
||||
if _, err := prov(dir).Lookup(context.Background(), discordUser()); err == nil {
|
||||
t.Fatal("expected an error for an ambiguous email")
|
||||
}
|
||||
if len(dir.updates) != 0 {
|
||||
t.Error("no account may be linked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLookupIdentityConflictByEmail(t *testing.T) {
|
||||
dir := newFakeDirectory(graphUser("x", "alice", "alice@example.com", "X", "999999999999999999"))
|
||||
if _, err := prov(dir).Lookup(context.Background(), discordUser()); !errors.Is(err, ErrIdentityConflict) {
|
||||
t.Fatalf("err = %v, want ErrIdentityConflict", err)
|
||||
}
|
||||
if len(dir.updates) != 0 {
|
||||
t.Error("conflicting account was modified")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateUsesChosenUsername(t *testing.T) {
|
||||
dir := newFakeDirectory()
|
||||
id, err := prov(dir).Create(context.Background(), discordUser(), "alice", true)
|
||||
if err != nil || id != "new-user-id" || len(dir.created) != 1 {
|
||||
t.Fatalf("id = %q created = %d err = %v", id, len(dir.created), err)
|
||||
}
|
||||
u := dir.created[0]
|
||||
if u.GetOnPremisesSamAccountName() != "alice" || u.GetDisplayName() != "Alice" || u.GetMail() != "alice@example.com" || !u.GetAccountEnabled() {
|
||||
t.Errorf("unexpected user %+v", u)
|
||||
}
|
||||
if linked, ok := discordIdentity(&u); !ok || linked != testDiscordID {
|
||||
t.Errorf("identity not linked: %+v", u.GetIdentities())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateUnverifiedEmailIsNotStored(t *testing.T) {
|
||||
dir := newFakeDirectory()
|
||||
du := discordUser()
|
||||
du.Verified = false
|
||||
if _, err := prov(dir).Create(context.Background(), du, "alice", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dir.created[0].HasMail() {
|
||||
t.Error("unverified email must not be stored")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateRejectsUsername(t *testing.T) {
|
||||
dir := newFakeDirectory(graphUser("x", "Bob", "", "Bob", ""))
|
||||
for _, name := range []string{"", "ab", "1alice", "a b", "alice/x", "alice@example.com", strings.Repeat("a", 33)} {
|
||||
if _, err := prov(dir).Create(context.Background(), discordUser(), name, true); !errors.Is(err, ErrUsernameInvalid) {
|
||||
t.Errorf("%q: err = %v, want ErrUsernameInvalid", name, err)
|
||||
}
|
||||
}
|
||||
if _, err := prov(dir).Create(context.Background(), discordUser(), "bob", true); !errors.Is(err, ErrUsernameTaken) {
|
||||
t.Errorf("err = %v, want ErrUsernameTaken", err)
|
||||
}
|
||||
if len(dir.created) != 0 {
|
||||
t.Error("no account may be created")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvisionErrors(t *testing.T) {
|
||||
p := prov(newFakeDirectory())
|
||||
if _, err := p.Lookup(context.Background(), &User{ID: "not-a-snowflake"}); err == nil {
|
||||
t.Error("expected an error for an invalid discord id")
|
||||
}
|
||||
if _, err := p.Create(context.Background(), nil, "alice", true); err == nil {
|
||||
t.Error("expected an error for a nil user")
|
||||
}
|
||||
dir := newFakeDirectory()
|
||||
dir.createErr = errors.New("graph returned 500")
|
||||
if _, err := prov(dir).Create(context.Background(), discordUser(), "alice", true); err == nil || !strings.Contains(err.Error(), "graph returned 500") {
|
||||
t.Errorf("err = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuggestUsername(t *testing.T) {
|
||||
for in, want := range map[string]string{"Alice": "alice", "bob.smith": "bob.smith", "1abc": "", "ab": ""} {
|
||||
if got := SuggestUsername(&User{Username: in}); got != want {
|
||||
t.Errorf("SuggestUsername(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHasIdentity(t *testing.T) {
|
||||
values := []string{" $ https://idp $ uuid", "$https://discord.com$" + testDiscordID}
|
||||
if !hasIdentity(values, IdentityIssuer, testDiscordID) {
|
||||
t.Error("identity not found")
|
||||
}
|
||||
if hasIdentity(values, IdentityIssuer, testDiscordID+"1") || hasIdentity([]string{"broken"}, IdentityIssuer, testDiscordID) {
|
||||
t.Error("unexpected match")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// RegistrationSettings controls who may create a new account and whether new
|
||||
// accounts need an administrator's approval. Administrators manage it in the
|
||||
// Admin Settings UI.
|
||||
type RegistrationSettings struct {
|
||||
// AllowRegistration is the master switch for new accounts.
|
||||
AllowRegistration bool `json:"allow_registration"`
|
||||
// AllowWeb allows the username/email/password form on the login page.
|
||||
AllowWeb bool `json:"allow_web"`
|
||||
// AllowDiscord allows Discord users without an account to create one.
|
||||
AllowDiscord bool `json:"allow_discord"`
|
||||
// RequireApproval creates new accounts disabled until an admin approves them.
|
||||
RequireApproval bool `json:"require_approval"`
|
||||
}
|
||||
|
||||
// DefaultRegistrationSettings keeps the behaviour of installations without a
|
||||
// registration file: Discord users can sign up, there is no web form and no
|
||||
// approval step.
|
||||
func DefaultRegistrationSettings() RegistrationSettings {
|
||||
return RegistrationSettings{AllowRegistration: true, AllowDiscord: true}
|
||||
}
|
||||
|
||||
// WebAllowed reports whether the web signup form is open.
|
||||
func (s RegistrationSettings) WebAllowed() bool { return s.AllowRegistration && s.AllowWeb }
|
||||
|
||||
// DiscordAllowed reports whether new Discord users may create an account.
|
||||
func (s RegistrationSettings) DiscordAllowed() bool { return s.AllowRegistration && s.AllowDiscord }
|
||||
|
||||
// PublicRegistration is returned by the unauthenticated settings endpoint.
|
||||
// It only exposes what the login page needs.
|
||||
type PublicRegistration struct {
|
||||
Web bool `json:"web"`
|
||||
Discord bool `json:"discord"`
|
||||
// DiscordLogin reports whether the Discord button is shown at all.
|
||||
DiscordLogin bool `json:"discord_login"`
|
||||
}
|
||||
|
||||
// RegistrationStore persists RegistrationSettings as a JSON file (mode 0600)
|
||||
// and serves reads from memory, so saved values take effect immediately.
|
||||
type RegistrationStore struct {
|
||||
path string
|
||||
mu sync.RWMutex
|
||||
cur RegistrationSettings
|
||||
}
|
||||
|
||||
// NewRegistrationStore loads the settings from path. A missing file or a
|
||||
// missing field means the default value.
|
||||
func NewRegistrationStore(path string) (*RegistrationStore, error) {
|
||||
s := &RegistrationStore{path: path, cur: DefaultRegistrationSettings()}
|
||||
if err := readJSONFile(path, &s.cur); err != nil {
|
||||
return nil, fmt.Errorf("load registration settings: %w", err)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// Get returns the current settings.
|
||||
func (s *RegistrationStore) Get() RegistrationSettings {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.cur
|
||||
}
|
||||
|
||||
// Save persists the settings.
|
||||
func (s *RegistrationStore) Save(n RegistrationSettings) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if err := writeJSONFile(s.path, n); err != nil {
|
||||
return fmt.Errorf("save registration settings: %w", err)
|
||||
}
|
||||
s.cur = n
|
||||
return nil
|
||||
}
|
||||
|
||||
// PublicRegistration returns what the login page may offer. It is the same
|
||||
// data the unauthenticated registration endpoint returns.
|
||||
func (h *Handler) PublicRegistration() PublicRegistration { return h.publicRegistration() }
|
||||
|
||||
func (h *Handler) publicRegistration() PublicRegistration {
|
||||
reg := h.opt.Registration.Get()
|
||||
discordLogin := h.opt.Store.Get().Ready()
|
||||
return PublicRegistration{
|
||||
Web: reg.WebAllowed(),
|
||||
Discord: discordLogin && reg.DiscordAllowed(),
|
||||
DiscordLogin: discordLogin,
|
||||
}
|
||||
}
|
||||
|
||||
// getPublicRegistration serves GET /oauth2/discord/registration without
|
||||
// authentication.
|
||||
func (h *Handler) getPublicRegistration(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, h.publicRegistration())
|
||||
}
|
||||
|
||||
func (h *Handler) getRegistration(w http.ResponseWriter, r *http.Request) {
|
||||
if status, err := h.opt.Admin.AuthorizeAdmin(r); err != nil {
|
||||
writeJSONError(w, status, "accessDenied", "", http.StatusText(status))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, h.opt.Registration.Get())
|
||||
}
|
||||
|
||||
func (h *Handler) putRegistration(w http.ResponseWriter, r *http.Request) {
|
||||
if status, err := h.opt.Admin.AuthorizeAdmin(r); err != nil {
|
||||
writeJSONError(w, status, "accessDenied", "", http.StatusText(status))
|
||||
return
|
||||
}
|
||||
dec := json.NewDecoder(io.LimitReader(r.Body, 4<<10))
|
||||
dec.DisallowUnknownFields()
|
||||
var n RegistrationSettings
|
||||
if err := dec.Decode(&n); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "invalidRequest", "", "invalid JSON body")
|
||||
return
|
||||
}
|
||||
if err := h.opt.Registration.Save(n); err != nil {
|
||||
h.opt.Logger.Error().Err(err).Msg("discord: could not save registration settings")
|
||||
writeJSONError(w, http.StatusInternalServerError, "generalException", "", "could not save settings")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, n)
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRegistrationStoreDefaults(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "registration.json")
|
||||
s, err := NewRegistrationStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.Get() != DefaultRegistrationSettings() {
|
||||
t.Fatalf("defaults = %+v", s.Get())
|
||||
}
|
||||
// A field missing from the file keeps its default.
|
||||
if err := os.WriteFile(path, []byte(`{"allow_web":true}`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err = NewRegistrationStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := s.Get(); !got.AllowRegistration || !got.AllowDiscord || !got.AllowWeb || got.RequireApproval {
|
||||
t.Fatalf("partial file = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationStorePersists(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "registration.json")
|
||||
s, _ := NewRegistrationStore(path)
|
||||
n := RegistrationSettings{AllowRegistration: true, AllowWeb: false, AllowDiscord: true, RequireApproval: true}
|
||||
if err := s.Save(n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reloaded, err := NewRegistrationStore(path)
|
||||
if err != nil || reloaded.Get() != n {
|
||||
t.Fatalf("reloaded = %+v, %v", reloaded.Get(), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationMasterSwitch(t *testing.T) {
|
||||
s := RegistrationSettings{AllowWeb: true, AllowDiscord: true}
|
||||
if s.WebAllowed() || s.DiscordAllowed() {
|
||||
t.Fatal("routes must be closed when registration is off")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublicRegistration(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
if err := h.reg.Save(RegistrationSettings{AllowRegistration: true, AllowDiscord: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.admin.status = http.StatusUnauthorized // the public endpoint needs no auth
|
||||
rec := h.do(http.MethodGet, "/oauth2/discord/registration", nil)
|
||||
var p PublicRegistration
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &p); err != nil || rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d body = %s", rec.Code, rec.Body)
|
||||
}
|
||||
if p.Web || !p.Discord || !p.DiscordLogin {
|
||||
t.Fatalf("public = %+v", p)
|
||||
}
|
||||
|
||||
// Without a configured Discord login, Discord signup is not offered.
|
||||
if err := h.store.Save(Settings{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p = PublicRegistration{}
|
||||
rec = h.do(http.MethodGet, "/oauth2/discord/registration", nil)
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &p)
|
||||
if p.Discord || p.DiscordLogin {
|
||||
t.Fatalf("public without discord = %+v", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminRegistrationAPI(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
body := `{"allow_registration":true,"allow_web":true,"allow_discord":false,"require_approval":true}`
|
||||
rec := h.do(http.MethodPut, "/oauth2/discord/admin/registration", strings.NewReader(body))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("put status = %d body = %s", rec.Code, rec.Body)
|
||||
}
|
||||
want := RegistrationSettings{AllowRegistration: true, AllowWeb: true, RequireApproval: true}
|
||||
if h.reg.Get() != want {
|
||||
t.Fatalf("stored = %+v", h.reg.Get())
|
||||
}
|
||||
|
||||
if rec := h.do(http.MethodPut, "/oauth2/discord/admin/registration", strings.NewReader(`{"unknown":1}`)); rec.Code != http.StatusBadRequest {
|
||||
t.Errorf("unknown field status = %d", rec.Code)
|
||||
}
|
||||
|
||||
h.admin.status = http.StatusForbidden
|
||||
for _, m := range []string{http.MethodGet, http.MethodPut} {
|
||||
if rec := h.do(m, "/oauth2/discord/admin/registration", strings.NewReader(body)); rec.Code != http.StatusForbidden {
|
||||
t.Errorf("%s without permission = %d", m, rec.Code)
|
||||
}
|
||||
}
|
||||
if h.reg.Get() != want {
|
||||
t.Error("settings changed without permission")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/libregraph/lico/identifier"
|
||||
)
|
||||
|
||||
// LicoSessionIssuer writes the regular lico logon cookie (__Secure-KKT) for
|
||||
// an oCIS user, the same cookie the username/password form produces.
|
||||
type LicoSessionIssuer struct {
|
||||
Identifier *identifier.Identifier
|
||||
// SubAttribute is the LDAP attribute lico maps the subject from
|
||||
// (LDAP_SUB_ATTRIBUTES, ownCloudUUID by default).
|
||||
SubAttribute string
|
||||
}
|
||||
|
||||
// EntryID returns the lico ldap backend entry ID for an oCIS user ID.
|
||||
func (s LicoSessionIssuer) EntryID(userID string) string {
|
||||
return url.Values{s.SubAttribute: {userID}}.Encode()
|
||||
}
|
||||
|
||||
// IssueLogon implements SessionIssuer.
|
||||
func (s LicoSessionIssuer) IssueLogon(ctx context.Context, w http.ResponseWriter, userID string) error {
|
||||
if s.Identifier == nil {
|
||||
return errors.New("lico identifier is not available")
|
||||
}
|
||||
if userID == "" {
|
||||
return errors.New("empty user id")
|
||||
}
|
||||
u, err := s.Identifier.GetUserFromID(ctx, s.EntryID(userID), nil, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve user in idp backend: %w", err)
|
||||
}
|
||||
if u == nil || u.Subject() == "" {
|
||||
return errors.New("user not found in idp backend")
|
||||
}
|
||||
u.SetLogonAt(time.Now())
|
||||
return s.Identifier.WriteLogonCookie(w, u)
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
// Package discord implements the Discord OAuth2 login for Reverse Cloud: the
|
||||
// admin managed settings, the Discord API client, the guild membership check
|
||||
// and the HTTP handlers mounted by the idp service.
|
||||
package discord
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Settings holds the Discord login configuration that administrators manage
|
||||
// from the Admin Settings UI.
|
||||
type Settings struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
ClientID string `json:"client_id"`
|
||||
ClientSecret string `json:"client_secret"`
|
||||
AllowedGuildID string `json:"allowed_guild_id"`
|
||||
}
|
||||
|
||||
// Ready reports whether Discord login can be offered to users.
|
||||
func (s Settings) Ready() bool {
|
||||
return s.Enabled && s.ClientID != "" && s.ClientSecret != "" && s.AllowedGuildID != ""
|
||||
}
|
||||
|
||||
// Discord IDs (snowflakes) are unsigned 64 bit integers in decimal notation.
|
||||
var snowflake = regexp.MustCompile(`^[0-9]{15,21}$`)
|
||||
|
||||
// ValidationError describes an invalid settings field.
|
||||
type ValidationError struct {
|
||||
Field string
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e *ValidationError) Error() string { return e.Field + ": " + e.Message }
|
||||
|
||||
// Validate checks the field formats. All fields are required when enabled.
|
||||
func (s Settings) Validate() error {
|
||||
if s.ClientID != "" && !snowflake.MatchString(s.ClientID) {
|
||||
return &ValidationError{Field: "client_id", Message: "must be a numeric Discord application ID"}
|
||||
}
|
||||
if s.AllowedGuildID != "" && !snowflake.MatchString(s.AllowedGuildID) {
|
||||
return &ValidationError{Field: "allowed_guild_id", Message: "must be a numeric Discord server ID"}
|
||||
}
|
||||
if len(s.ClientSecret) > 256 || strings.ContainsAny(s.ClientSecret, " \t\r\n") {
|
||||
return &ValidationError{Field: "client_secret", Message: "is not a valid client secret"}
|
||||
}
|
||||
if s.Enabled {
|
||||
switch {
|
||||
case s.ClientID == "":
|
||||
return &ValidationError{Field: "client_id", Message: "is required when Discord login is enabled"}
|
||||
case s.ClientSecret == "":
|
||||
return &ValidationError{Field: "client_secret", Message: "is required when Discord login is enabled"}
|
||||
case s.AllowedGuildID == "":
|
||||
return &ValidationError{Field: "allowed_guild_id", Message: "is required when Discord login is enabled"}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// View is the representation returned by the admin API. It never contains
|
||||
// the client secret.
|
||||
type View struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
ClientID string `json:"client_id"`
|
||||
AllowedGuildID string `json:"allowed_guild_id"`
|
||||
ClientSecretSet bool `json:"client_secret_set"`
|
||||
RedirectURI string `json:"redirect_uri"`
|
||||
}
|
||||
|
||||
// View returns the public representation of the settings.
|
||||
func (s Settings) View(redirectURI string) View {
|
||||
return View{
|
||||
Enabled: s.Enabled,
|
||||
ClientID: s.ClientID,
|
||||
AllowedGuildID: s.AllowedGuildID,
|
||||
ClientSecretSet: s.ClientSecret != "",
|
||||
RedirectURI: redirectURI,
|
||||
}
|
||||
}
|
||||
|
||||
// Update is the payload accepted by the admin API. An absent or empty client
|
||||
// secret keeps the stored one, so the UI never has to know the secret.
|
||||
type Update struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
ClientID string `json:"client_id"`
|
||||
ClientSecret *string `json:"client_secret,omitempty"`
|
||||
AllowedGuildID string `json:"allowed_guild_id"`
|
||||
}
|
||||
|
||||
// Apply merges the update into the current settings.
|
||||
func (u Update) Apply(cur Settings) Settings {
|
||||
n := Settings{
|
||||
Enabled: u.Enabled,
|
||||
ClientID: strings.TrimSpace(u.ClientID),
|
||||
ClientSecret: cur.ClientSecret,
|
||||
AllowedGuildID: strings.TrimSpace(u.AllowedGuildID),
|
||||
}
|
||||
if u.ClientSecret != nil {
|
||||
if secret := strings.TrimSpace(*u.ClientSecret); secret != "" {
|
||||
n.ClientSecret = secret
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// Store persists the settings as a JSON file (mode 0600) and serves reads
|
||||
// from memory, so saved values take effect immediately.
|
||||
type Store struct {
|
||||
path string
|
||||
mu sync.RWMutex
|
||||
cur Settings
|
||||
}
|
||||
|
||||
// NewStore loads the settings from path. A missing file means defaults.
|
||||
func NewStore(path string) (*Store, error) {
|
||||
s := &Store{path: path}
|
||||
if err := readJSONFile(path, &s.cur); err != nil {
|
||||
return nil, fmt.Errorf("load discord settings: %w", err)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// Get returns the current settings.
|
||||
func (s *Store) Get() Settings {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.cur
|
||||
}
|
||||
|
||||
// Save validates and persists the settings.
|
||||
func (s *Store) Save(n Settings) error {
|
||||
if err := n.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if err := writeJSONFile(s.path, n); err != nil {
|
||||
return fmt.Errorf("save discord settings: %w", err)
|
||||
}
|
||||
s.cur = n
|
||||
return nil
|
||||
}
|
||||
|
||||
// readJSONFile decodes path into out. A missing file is not an error.
|
||||
func readJSONFile(path string, out any) error {
|
||||
b, err := os.ReadFile(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := json.Unmarshal(b, out); err != nil {
|
||||
return fmt.Errorf("parse %s: %w", path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// writeJSONFile atomically replaces path with the JSON encoding of v.
|
||||
func writeJSONFile(path string, v any) error {
|
||||
data, err := json.MarshalIndent(v, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dir := filepath.Dir(path)
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := os.CreateTemp(dir, ".discord-*.tmp")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := f.Name()
|
||||
defer os.Remove(tmp) // no-op after a successful rename
|
||||
if err := f.Chmod(0o600); err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
if _, err := f.Write(data); err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
if err := f.Sync(); err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp, path)
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func validSettings() Settings {
|
||||
return Settings{Enabled: true, ClientID: testClientID, ClientSecret: testSecret, AllowedGuildID: "223456789012345678"}
|
||||
}
|
||||
|
||||
func TestSettingsValidate(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mod func(*Settings)
|
||||
field string
|
||||
}{
|
||||
{"valid", func(*Settings) {}, ""},
|
||||
{"disabled and empty", func(s *Settings) { *s = Settings{} }, ""},
|
||||
{"non numeric client id", func(s *Settings) { s.ClientID = "abc" }, "client_id"},
|
||||
{"non numeric guild id", func(s *Settings) { s.AllowedGuildID = "my-server" }, "allowed_guild_id"},
|
||||
{"short guild id", func(s *Settings) { s.AllowedGuildID = "12345" }, "allowed_guild_id"},
|
||||
{"secret with whitespace", func(s *Settings) { s.ClientSecret = "a b" }, "client_secret"},
|
||||
{"secret too long", func(s *Settings) { s.ClientSecret = strings.Repeat("x", 257) }, "client_secret"},
|
||||
{"enabled without client id", func(s *Settings) { s.ClientID = "" }, "client_id"},
|
||||
{"enabled without secret", func(s *Settings) { s.ClientSecret = "" }, "client_secret"},
|
||||
{"enabled without guild", func(s *Settings) { s.AllowedGuildID = "" }, "allowed_guild_id"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := validSettings()
|
||||
tt.mod(&s)
|
||||
err := s.Validate()
|
||||
if tt.field == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
var ve *ValidationError
|
||||
if !errors.As(err, &ve) || ve.Field != tt.field {
|
||||
t.Fatalf("err = %v, want validation error on %s", err, tt.field)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorePersistsSettings(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "sub", "discord.json")
|
||||
s, err := NewStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.Get() != (Settings{}) {
|
||||
t.Fatalf("missing file should give defaults, got %+v", s.Get())
|
||||
}
|
||||
|
||||
if err := s.Save(validSettings()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.Get() != validSettings() {
|
||||
t.Errorf("Get after Save = %+v", s.Get())
|
||||
}
|
||||
st, err := os.Stat(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if perm := st.Mode().Perm(); perm != 0o600 {
|
||||
t.Errorf("file mode = %o, want 600", perm)
|
||||
}
|
||||
|
||||
reloaded, err := NewStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if reloaded.Get() != validSettings() {
|
||||
t.Errorf("reloaded = %+v", reloaded.Get())
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreRejectsInvalidSettings(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "discord.json")
|
||||
s, _ := NewStore(path)
|
||||
bad := validSettings()
|
||||
bad.AllowedGuildID = "x"
|
||||
var ve *ValidationError
|
||||
if err := s.Save(bad); !errors.As(err, &ve) {
|
||||
t.Fatalf("err = %v, want ValidationError", err)
|
||||
}
|
||||
if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Error("invalid settings were written to disk")
|
||||
}
|
||||
if s.Get() != (Settings{}) {
|
||||
t.Error("invalid settings were applied in memory")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreCorruptFile(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "discord.json")
|
||||
if err := os.WriteFile(path, []byte("{not json"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := NewStore(path); err == nil {
|
||||
t.Fatal("expected an error for a corrupt settings file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateApplyKeepsSecret(t *testing.T) {
|
||||
cur := validSettings()
|
||||
empty, blank, next := "", " ", " new-secret "
|
||||
|
||||
if got := (Update{Enabled: true, ClientID: " 323456789012345678 "}).Apply(cur); got.ClientSecret != testSecret || got.ClientID != "323456789012345678" {
|
||||
t.Errorf("nil secret: %+v", got)
|
||||
}
|
||||
if got := (Update{ClientSecret: &empty}).Apply(cur); got.ClientSecret != testSecret {
|
||||
t.Errorf("empty secret replaced the stored one")
|
||||
}
|
||||
if got := (Update{ClientSecret: &blank}).Apply(cur); got.ClientSecret != testSecret {
|
||||
t.Errorf("blank secret replaced the stored one")
|
||||
}
|
||||
if got := (Update{ClientSecret: &next}).Apply(cur); got.ClientSecret != "new-secret" {
|
||||
t.Errorf("secret = %q, want new-secret", got.ClientSecret)
|
||||
}
|
||||
}
|
||||
|
||||
func TestViewOmitsSecret(t *testing.T) {
|
||||
v := validSettings().View("https://cloud.example.com/oauth2/discord/callback")
|
||||
b, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(string(b), testSecret) {
|
||||
t.Fatalf("view leaks the client secret: %s", b)
|
||||
}
|
||||
if !v.ClientSecretSet || v.RedirectURI == "" {
|
||||
t.Errorf("unexpected view %+v", v)
|
||||
}
|
||||
if (Settings{}).View("").ClientSecretSet {
|
||||
t.Error("ClientSecretSet must be false without a secret")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLicoSessionIssuerEntryID(t *testing.T) {
|
||||
s := LicoSessionIssuer{SubAttribute: "ownCloudUUID"}
|
||||
if got := s.EntryID("4c510ada-c86b-4815-8820-42cdf82c3d51"); got != "ownCloudUUID=4c510ada-c86b-4815-8820-42cdf82c3d51" {
|
||||
t.Errorf("EntryID = %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
signupCookieName = "__Secure-RC-Discord-Signup"
|
||||
signupTTL = 10 * time.Minute
|
||||
signupPurpose = "discord-signup"
|
||||
maxSignupBody = 8 << 10
|
||||
)
|
||||
|
||||
// SignupForm is rendered when a Discord user without an account has to
|
||||
// choose the username of the account that will be created.
|
||||
type SignupForm struct {
|
||||
Action string
|
||||
Token string
|
||||
Username string
|
||||
DisplayName string
|
||||
// ErrCode is set when the submitted username was rejected.
|
||||
ErrCode string
|
||||
}
|
||||
|
||||
// signupData is kept in a signed cookie between the callback and the form
|
||||
// submission. It carries the Discord profile checked in the callback, so the
|
||||
// guild membership check does not have to be repeated.
|
||||
type signupData struct {
|
||||
Token string `json:"t"`
|
||||
Query string `json:"q"`
|
||||
Exp int64 `json:"e"`
|
||||
ID string `json:"id"`
|
||||
Username string `json:"u"`
|
||||
GlobalName string `json:"g,omitempty"`
|
||||
// Email is only set when Discord marked it as verified.
|
||||
Email string `json:"m,omitempty"`
|
||||
}
|
||||
|
||||
func (d signupData) user() *User {
|
||||
return &User{ID: d.ID, Username: d.Username, GlobalName: d.GlobalName, Email: d.Email, Verified: d.Email != ""}
|
||||
}
|
||||
|
||||
func (c stateCodec) mac(purpose, payload string) string {
|
||||
m := hmac.New(sha256.New, c.key)
|
||||
m.Write([]byte(purpose + ":" + payload))
|
||||
return base64.RawURLEncoding.EncodeToString(m.Sum(nil))
|
||||
}
|
||||
|
||||
// seal returns v as a signed cookie value bound to purpose.
|
||||
func (c stateCodec) seal(purpose string, v any) (string, error) {
|
||||
b, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
p := base64.RawURLEncoding.EncodeToString(b)
|
||||
return p + "." + c.mac(purpose, p), nil
|
||||
}
|
||||
|
||||
// open verifies a value produced by seal and decodes it into out.
|
||||
func (c stateCodec) open(purpose, value string, out any) error {
|
||||
payload, sig, ok := strings.Cut(value, ".")
|
||||
if !ok || !hmac.Equal([]byte(sig), []byte(c.mac(purpose, payload))) {
|
||||
return errInvalidState
|
||||
}
|
||||
b, err := base64.RawURLEncoding.DecodeString(payload)
|
||||
if err != nil {
|
||||
return errInvalidState
|
||||
}
|
||||
if err := json.Unmarshal(b, out); err != nil {
|
||||
return errInvalidState
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Handler) signupCookie(value string, maxAge int) *http.Cookie {
|
||||
return &http.Cookie{
|
||||
Name: signupCookieName,
|
||||
Value: value,
|
||||
Path: routePrefix + "/",
|
||||
MaxAge: maxAge,
|
||||
Secure: true,
|
||||
HttpOnly: true,
|
||||
// Only sent with the same-origin form submission.
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) signupForm(token string, u *User, username, code string) SignupForm {
|
||||
return SignupForm{
|
||||
Action: routePrefix + "/signup",
|
||||
Token: token,
|
||||
Username: username,
|
||||
DisplayName: u.DisplayName(),
|
||||
ErrCode: code,
|
||||
}
|
||||
}
|
||||
|
||||
// startSignup asks a Discord user without an account for the username.
|
||||
func (h *Handler) startSignup(w http.ResponseWriter, r *http.Request, u *User, query string) {
|
||||
token, err := randomToken(32)
|
||||
if err != nil {
|
||||
h.opt.Logger.Error().Err(err).Msg("discord: could not generate signup token")
|
||||
h.opt.Render.Error(w, r, http.StatusInternalServerError, ErrCodeServer)
|
||||
return
|
||||
}
|
||||
value, err := h.state.seal(signupPurpose, signupData{
|
||||
Token: token,
|
||||
Query: query,
|
||||
Exp: h.opt.Now().Add(signupTTL).Unix(),
|
||||
ID: u.ID,
|
||||
Username: u.Username,
|
||||
GlobalName: u.GlobalName,
|
||||
Email: u.VerifiedEmail(),
|
||||
})
|
||||
if err != nil {
|
||||
h.opt.Render.Error(w, r, http.StatusInternalServerError, ErrCodeServer)
|
||||
return
|
||||
}
|
||||
http.SetCookie(w, h.signupCookie(value, int(signupTTL/time.Second)))
|
||||
h.opt.Render.Signup(w, r, http.StatusOK, h.signupForm(token, u, SuggestUsername(u), ""))
|
||||
}
|
||||
|
||||
// signup handles the submitted username form.
|
||||
func (h *Handler) signup(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
logger := h.opt.Logger.With().Str("component", "discord").Logger()
|
||||
|
||||
if !h.opt.Store.Get().Ready() {
|
||||
h.opt.Render.Error(w, r, http.StatusNotFound, ErrCodeDisabled)
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxSignupBody)
|
||||
if err := r.ParseForm(); err != nil {
|
||||
h.opt.Render.Error(w, r, http.StatusBadRequest, ErrCodeInvalidState)
|
||||
return
|
||||
}
|
||||
c, err := r.Cookie(signupCookieName)
|
||||
if err != nil {
|
||||
h.opt.Render.Error(w, r, http.StatusBadRequest, ErrCodeInvalidState)
|
||||
return
|
||||
}
|
||||
var sd signupData
|
||||
if err := h.state.open(signupPurpose, c.Value, &sd); err != nil {
|
||||
logger.Info().Msg("discord signup with invalid cookie")
|
||||
h.opt.Render.Error(w, r, http.StatusBadRequest, ErrCodeInvalidState)
|
||||
return
|
||||
}
|
||||
if h.opt.Now().Unix() > sd.Exp {
|
||||
http.SetCookie(w, h.signupCookie("", -1))
|
||||
h.opt.Render.Error(w, r, http.StatusBadRequest, ErrCodeExpired)
|
||||
return
|
||||
}
|
||||
token := r.PostForm.Get("token")
|
||||
if token == "" || subtle.ConstantTimeCompare([]byte(token), []byte(sd.Token)) != 1 {
|
||||
h.opt.Render.Error(w, r, http.StatusBadRequest, ErrCodeInvalidState)
|
||||
return
|
||||
}
|
||||
|
||||
du := sd.user()
|
||||
// The account may have been created meanwhile, e.g. in another tab.
|
||||
userID, err := h.opt.Provisioner.Lookup(ctx, du)
|
||||
if err != nil {
|
||||
logger.Error().Err(err).Str("discord_id", du.ID).Msg("discord user lookup failed")
|
||||
h.opt.Render.Error(w, r, http.StatusInternalServerError, ErrCodeProvision)
|
||||
return
|
||||
}
|
||||
if userID == "" {
|
||||
reg := h.opt.Registration.Get()
|
||||
if !reg.DiscordAllowed() {
|
||||
http.SetCookie(w, h.signupCookie("", -1))
|
||||
h.opt.Render.Error(w, r, http.StatusForbidden, ErrCodeRegistrationClosed)
|
||||
return
|
||||
}
|
||||
username := strings.TrimSpace(r.PostForm.Get("username"))
|
||||
userID, err = h.opt.Provisioner.Create(ctx, du, username, !reg.RequireApproval)
|
||||
switch {
|
||||
case errors.Is(err, ErrUsernameInvalid):
|
||||
h.opt.Render.Signup(w, r, http.StatusBadRequest, h.signupForm(sd.Token, du, username, ErrCodeUsernameInvalid))
|
||||
return
|
||||
case errors.Is(err, ErrUsernameTaken):
|
||||
h.opt.Render.Signup(w, r, http.StatusConflict, h.signupForm(sd.Token, du, username, ErrCodeUsernameTaken))
|
||||
return
|
||||
case err != nil:
|
||||
logger.Error().Err(err).Str("discord_id", du.ID).Msg("discord user provisioning failed")
|
||||
h.opt.Render.Error(w, r, http.StatusInternalServerError, ErrCodeProvision)
|
||||
return
|
||||
}
|
||||
logger.Info().Str("discord_id", du.ID).Str("user_id", userID).Msg("created account for discord user")
|
||||
if reg.RequireApproval {
|
||||
err := h.opt.Pending.Add(PendingUser{
|
||||
UserID: userID,
|
||||
Username: username,
|
||||
DisplayName: du.DisplayName(),
|
||||
Mail: du.VerifiedEmail(),
|
||||
Source: SourceDiscord,
|
||||
RequestedAt: h.opt.Now().UTC(),
|
||||
})
|
||||
if err != nil {
|
||||
// The account is disabled, so it stays locked until an admin enables it.
|
||||
logger.Error().Err(err).Str("user_id", userID).Msg("could not record pending account")
|
||||
}
|
||||
http.SetCookie(w, h.signupCookie("", -1))
|
||||
h.opt.Render.Error(w, r, http.StatusOK, ErrCodeRegistrationSubmitted)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
http.SetCookie(w, h.signupCookie("", -1))
|
||||
if h.opt.Pending.IsPending(userID) {
|
||||
h.opt.Render.Error(w, r, http.StatusForbidden, ErrCodePendingApproval)
|
||||
return
|
||||
}
|
||||
if err := h.opt.Sessions.IssueLogon(ctx, w, userID); err != nil {
|
||||
logger.Error().Err(err).Str("user_id", userID).Msg("discord logon cookie failed")
|
||||
h.opt.Render.Error(w, r, http.StatusInternalServerError, ErrCodeServer)
|
||||
return
|
||||
}
|
||||
h.opt.Render.Continue(w, r, h.continueTarget(sd.Query))
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func findCookie(rec *httptest.ResponseRecorder, name string) *http.Cookie {
|
||||
for _, c := range rec.Result().Cookies() {
|
||||
if c.Name == name {
|
||||
return c
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *harness) postSignup(form url.Values, cookies ...*http.Cookie) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodPost, "/oauth2/discord/signup", strings.NewReader(form.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
for _, c := range cookies {
|
||||
req.AddCookie(c)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
h.router.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
// startSignup runs the Discord login for a user without an account and
|
||||
// returns the rendered form and the signup cookie.
|
||||
func (h *harness) startSignup(query string) (SignupForm, *http.Cookie) {
|
||||
h.t.Helper()
|
||||
h.prov.missing = true
|
||||
state, c := h.login(query)
|
||||
rec := h.callback(cbQuery(testCode, state), c)
|
||||
if rec.Code != http.StatusOK || h.render.signup == nil {
|
||||
h.t.Fatalf("status = %d code = %q, want signup form", rec.Code, h.render.code)
|
||||
}
|
||||
ck := findCookie(rec, signupCookieName)
|
||||
if ck == nil {
|
||||
h.t.Fatal("signup cookie not set")
|
||||
}
|
||||
return *h.render.signup, ck
|
||||
}
|
||||
|
||||
func TestCallbackWithoutAccountAsksForUsername(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
f, ck := h.startSignup("client_id=web")
|
||||
if f.Username != "alice" || f.DisplayName != "Alice" || f.Token == "" || f.Action != "/oauth2/discord/signup" || f.ErrCode != "" {
|
||||
t.Errorf("unexpected form %+v", f)
|
||||
}
|
||||
if !ck.HttpOnly || !ck.Secure || ck.SameSite != http.SameSiteStrictMode || ck.Path != "/oauth2/discord/" {
|
||||
t.Errorf("unexpected signup cookie %+v", ck)
|
||||
}
|
||||
if h.sess.userID != "" || len(h.prov.created) != 0 {
|
||||
t.Error("no account may be created or logged on before the username is chosen")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignupCreatesAccountAndLogsOn(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
f, ck := h.startSignup("client_id=web&state=oidc-state")
|
||||
rec := h.postSignup(url.Values{"token": {f.Token}, "username": {" alice2 "}}, ck)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d code = %q", rec.Code, h.render.code)
|
||||
}
|
||||
if len(h.prov.created) != 1 || h.prov.created[0] != "alice2" {
|
||||
t.Fatalf("created = %v", h.prov.created)
|
||||
}
|
||||
if h.prov.user.ID != h.fd.user.ID || h.prov.user.VerifiedEmail() != "alice@example.com" {
|
||||
t.Errorf("discord profile not carried over: %+v", h.prov.user)
|
||||
}
|
||||
if h.sess.userID != h.prov.id {
|
||||
t.Errorf("logon issued for %q, want %q", h.sess.userID, h.prov.id)
|
||||
}
|
||||
target, _ := url.Parse(h.render.target)
|
||||
if target.Path != testAuthorizePath || target.Query().Get("state") != "oidc-state" {
|
||||
t.Errorf("target = %q", h.render.target)
|
||||
}
|
||||
if c := findCookie(rec, signupCookieName); c == nil || c.MaxAge >= 0 {
|
||||
t.Error("signup cookie was not cleared")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignupRejectedUsernameShowsFormAgain(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
err error
|
||||
wantStatus int
|
||||
wantCode string
|
||||
}{
|
||||
{"invalid", ErrUsernameInvalid, http.StatusBadRequest, ErrCodeUsernameInvalid},
|
||||
{"taken", ErrUsernameTaken, http.StatusConflict, ErrCodeUsernameTaken},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
f, ck := h.startSignup("")
|
||||
h.prov.createErr = tt.err
|
||||
rec := h.postSignup(url.Values{"token": {f.Token}, "username": {"bob"}}, ck)
|
||||
if rec.Code != tt.wantStatus || h.render.signup.ErrCode != tt.wantCode {
|
||||
t.Fatalf("status = %d form = %+v", rec.Code, h.render.signup)
|
||||
}
|
||||
if h.render.signup.Username != "bob" || h.render.signup.Token != f.Token {
|
||||
t.Errorf("form lost the input: %+v", h.render.signup)
|
||||
}
|
||||
if h.sess.userID != "" {
|
||||
t.Error("logon issued for a rejected username")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignupUsesAccountCreatedMeanwhile(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
f, ck := h.startSignup("")
|
||||
h.prov.missing = false
|
||||
if rec := h.postSignup(url.Values{"token": {f.Token}, "username": {"bob"}}, ck); rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d", rec.Code)
|
||||
}
|
||||
if len(h.prov.created) != 0 || h.sess.userID != h.prov.id {
|
||||
t.Errorf("created = %v logon = %q", h.prov.created, h.sess.userID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignupUnverifiedEmailIsNotCarried(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.fd.user.Verified = false
|
||||
f, ck := h.startSignup("")
|
||||
h.postSignup(url.Values{"token": {f.Token}, "username": {"bob"}}, ck)
|
||||
if h.prov.user == nil || h.prov.user.VerifiedEmail() != "" {
|
||||
t.Errorf("unverified email was carried over: %+v", h.prov.user)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignupStateErrors(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
call func(h *harness) *httptest.ResponseRecorder
|
||||
wantCode string
|
||||
}{
|
||||
{"missing cookie", func(h *harness) *httptest.ResponseRecorder {
|
||||
f, _ := h.startSignup("")
|
||||
return h.postSignup(url.Values{"token": {f.Token}, "username": {"bob"}})
|
||||
}, ErrCodeInvalidState},
|
||||
{"wrong token", func(h *harness) *httptest.ResponseRecorder {
|
||||
_, ck := h.startSignup("")
|
||||
return h.postSignup(url.Values{"token": {"forged"}, "username": {"bob"}}, ck)
|
||||
}, ErrCodeInvalidState},
|
||||
{"tampered cookie", func(h *harness) *httptest.ResponseRecorder {
|
||||
f, ck := h.startSignup("")
|
||||
ck.Value = "x" + ck.Value
|
||||
return h.postSignup(url.Values{"token": {f.Token}, "username": {"bob"}}, ck)
|
||||
}, ErrCodeInvalidState},
|
||||
{"state cookie used as signup cookie", func(h *harness) *httptest.ResponseRecorder {
|
||||
f, _ := h.startSignup("")
|
||||
_, sc := h.login("")
|
||||
sc.Name = signupCookieName
|
||||
return h.postSignup(url.Values{"token": {f.Token}, "username": {"bob"}}, sc)
|
||||
}, ErrCodeInvalidState},
|
||||
{"expired", func(h *harness) *httptest.ResponseRecorder {
|
||||
f, ck := h.startSignup("")
|
||||
h.now = h.now.Add(signupTTL + time.Minute)
|
||||
return h.postSignup(url.Values{"token": {f.Token}, "username": {"bob"}}, ck)
|
||||
}, ErrCodeExpired},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
rec := tt.call(h)
|
||||
if rec.Code != http.StatusBadRequest || h.render.code != tt.wantCode {
|
||||
t.Fatalf("status = %d code = %q, want 400 %s", rec.Code, h.render.code, tt.wantCode)
|
||||
}
|
||||
if len(h.prov.created) != 0 || h.sess.userID != "" {
|
||||
t.Error("account created or logged on with an invalid signup")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
stateCookieName = "__Secure-RC-Discord-State"
|
||||
stateTTL = 10 * time.Minute
|
||||
routePrefix = "/oauth2/discord"
|
||||
)
|
||||
|
||||
var (
|
||||
errInvalidState = errors.New("invalid oauth2 state")
|
||||
errStateExpired = errors.New("oauth2 state expired")
|
||||
)
|
||||
|
||||
// stateData is stored in a signed cookie between /login and /callback. It
|
||||
// binds the state parameter to the browser (CSRF protection) and carries the
|
||||
// original OIDC authorize query.
|
||||
type stateData struct {
|
||||
State string `json:"s"`
|
||||
Query string `json:"q"`
|
||||
Exp int64 `json:"e"`
|
||||
// Mode is modeLink when a signed in user links Discord to the account
|
||||
// UserID; empty for the login flow.
|
||||
Mode string `json:"m,omitempty"`
|
||||
UserID string `json:"u,omitempty"`
|
||||
}
|
||||
|
||||
type stateCodec struct {
|
||||
key []byte
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func (c stateCodec) encode(d stateData) (string, error) {
|
||||
b, err := json.Marshal(d)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
p := base64.RawURLEncoding.EncodeToString(b)
|
||||
return p + "." + c.sign(p), nil
|
||||
}
|
||||
|
||||
func (c stateCodec) sign(payload string) string {
|
||||
m := hmac.New(sha256.New, c.key)
|
||||
m.Write([]byte("discord-state:" + payload))
|
||||
return base64.RawURLEncoding.EncodeToString(m.Sum(nil))
|
||||
}
|
||||
|
||||
// decode verifies the cookie value and that it belongs to state.
|
||||
func (c stateCodec) decode(value, state string) (stateData, error) {
|
||||
var d stateData
|
||||
payload, sig, ok := strings.Cut(value, ".")
|
||||
if !ok || !hmac.Equal([]byte(sig), []byte(c.sign(payload))) {
|
||||
return d, errInvalidState
|
||||
}
|
||||
b, err := base64.RawURLEncoding.DecodeString(payload)
|
||||
if err != nil {
|
||||
return d, errInvalidState
|
||||
}
|
||||
if err := json.Unmarshal(b, &d); err != nil {
|
||||
return d, errInvalidState
|
||||
}
|
||||
if c.now().Unix() > d.Exp {
|
||||
return d, errStateExpired
|
||||
}
|
||||
if state == "" || subtle.ConstantTimeCompare([]byte(d.State), []byte(state)) != 1 {
|
||||
return d, errInvalidState
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// randomToken returns n random bytes, base64url encoded.
|
||||
func randomToken(n int) (string, error) {
|
||||
b := make([]byte, n)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/mail"
|
||||
"net/url"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// loginPagePath is the idp login page the registration form links back to.
|
||||
const loginPagePath = "/signin/v1/identifier"
|
||||
|
||||
const (
|
||||
maxRegisterBody = 8 << 10
|
||||
minPasswordLen = 8
|
||||
maxPasswordLen = 256
|
||||
maxMailLen = 254
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrMailTaken means another account uses the email address.
|
||||
ErrMailTaken = errors.New("email address is already used")
|
||||
// ErrPasswordRejected means the graph password policy refused the password.
|
||||
ErrPasswordRejected = errors.New("password does not meet the password policy")
|
||||
)
|
||||
|
||||
// Error codes of the web registration form.
|
||||
const (
|
||||
ErrCodeMailInvalid = "registration_mail_invalid"
|
||||
ErrCodeMailTaken = "registration_mail_taken"
|
||||
ErrCodePasswordInvalid = "registration_password_invalid"
|
||||
ErrCodePasswordMismatch = "registration_password_mismatch"
|
||||
)
|
||||
|
||||
// WebUser is an account requested with the web registration form.
|
||||
type WebUser struct {
|
||||
Username string
|
||||
Mail string
|
||||
Password string
|
||||
}
|
||||
|
||||
// WebAccounts creates accounts from the web registration form.
|
||||
type WebAccounts interface {
|
||||
// CreateWebUser returns ErrUsernameInvalid, ErrUsernameTaken, ErrMailTaken
|
||||
// or ErrPasswordRejected for input the user has to change.
|
||||
CreateWebUser(ctx context.Context, u WebUser, enabled bool) (string, error)
|
||||
}
|
||||
|
||||
// RegisterForm is rendered for the web registration.
|
||||
type RegisterForm struct {
|
||||
Action string
|
||||
// Query is the OIDC query of the login page, kept to return there.
|
||||
Query string
|
||||
LoginURL string
|
||||
Username string
|
||||
Mail string
|
||||
ErrCode string
|
||||
}
|
||||
|
||||
func (h *Handler) newRegisterForm(query string) RegisterForm {
|
||||
login := loginPagePath
|
||||
if query != "" {
|
||||
login += "?" + query
|
||||
}
|
||||
return RegisterForm{Action: routePrefix + "/register", Query: query, LoginURL: login}
|
||||
}
|
||||
|
||||
// validQuery accepts the OIDC query of the login page.
|
||||
func validQuery(q string) bool {
|
||||
if len(q) > maxQueryLen {
|
||||
return false
|
||||
}
|
||||
_, err := url.ParseQuery(q)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func validMail(s string) bool {
|
||||
if s == "" || len(s) > maxMailLen {
|
||||
return false
|
||||
}
|
||||
a, err := mail.ParseAddress(s)
|
||||
return err == nil && a.Address == s && a.Name == ""
|
||||
}
|
||||
|
||||
// validateRegistration returns the error code of the first invalid field.
|
||||
// The graph password policy is checked when the account is created.
|
||||
func validateRegistration(f RegisterForm, password, confirm string) string {
|
||||
switch {
|
||||
case !ValidUsername(f.Username):
|
||||
return ErrCodeUsernameInvalid
|
||||
case !validMail(f.Mail):
|
||||
return ErrCodeMailInvalid
|
||||
case utf8.RuneCountInString(password) < minPasswordLen || len(password) > maxPasswordLen:
|
||||
return ErrCodePasswordInvalid
|
||||
case password != confirm:
|
||||
return ErrCodePasswordMismatch
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// sameOrigin rejects cross-site form posts: browsers send Origin (or at
|
||||
// least Referer) with a form POST, and it must be the public oCIS URL.
|
||||
func (h *Handler) sameOrigin(r *http.Request) bool {
|
||||
pub, err := url.Parse(h.opt.PublicURL)
|
||||
if err != nil || pub.Host == "" {
|
||||
return false
|
||||
}
|
||||
want := pub.Scheme + "://" + pub.Host
|
||||
if o := r.Header.Get("Origin"); o != "" {
|
||||
return o == want
|
||||
}
|
||||
if ref := r.Header.Get("Referer"); ref != "" {
|
||||
u, err := url.Parse(ref)
|
||||
return err == nil && u.Scheme+"://"+u.Host == want
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// getRegister serves GET /oauth2/discord/register.
|
||||
func (h *Handler) getRegister(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.opt.Registration.Get().WebAllowed() {
|
||||
h.opt.Render.Error(w, r, http.StatusForbidden, ErrCodeRegistrationClosed)
|
||||
return
|
||||
}
|
||||
if !validQuery(r.URL.RawQuery) {
|
||||
h.opt.Render.Error(w, r, http.StatusBadRequest, ErrCodeInvalidState)
|
||||
return
|
||||
}
|
||||
h.opt.Render.Register(w, r, http.StatusOK, h.newRegisterForm(r.URL.RawQuery))
|
||||
}
|
||||
|
||||
// postRegister serves POST /oauth2/discord/register.
|
||||
func (h *Handler) postRegister(w http.ResponseWriter, r *http.Request) {
|
||||
logger := h.opt.Logger.With().Str("component", "registration").Logger()
|
||||
reg := h.opt.Registration.Get()
|
||||
if !reg.WebAllowed() {
|
||||
h.opt.Render.Error(w, r, http.StatusForbidden, ErrCodeRegistrationClosed)
|
||||
return
|
||||
}
|
||||
if !h.sameOrigin(r) {
|
||||
h.opt.Render.Error(w, r, http.StatusForbidden, ErrCodeInvalidState)
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxRegisterBody)
|
||||
if err := r.ParseForm(); err != nil {
|
||||
h.opt.Render.Error(w, r, http.StatusBadRequest, ErrCodeInvalidState)
|
||||
return
|
||||
}
|
||||
q := r.PostForm.Get("q")
|
||||
if !validQuery(q) {
|
||||
h.opt.Render.Error(w, r, http.StatusBadRequest, ErrCodeInvalidState)
|
||||
return
|
||||
}
|
||||
f := h.newRegisterForm(q)
|
||||
f.Username = strings.TrimSpace(r.PostForm.Get("username"))
|
||||
f.Mail = strings.TrimSpace(r.PostForm.Get("mail"))
|
||||
password := r.PostForm.Get("password")
|
||||
if code := validateRegistration(f, password, r.PostForm.Get("password_confirm")); code != "" {
|
||||
f.ErrCode = code
|
||||
h.opt.Render.Register(w, r, http.StatusBadRequest, f)
|
||||
return
|
||||
}
|
||||
|
||||
userID, err := h.opt.WebAccounts.CreateWebUser(r.Context(), WebUser{Username: f.Username, Mail: f.Mail, Password: password}, !reg.RequireApproval)
|
||||
if err != nil {
|
||||
status, code := http.StatusInternalServerError, ""
|
||||
switch {
|
||||
case errors.Is(err, ErrUsernameInvalid):
|
||||
status, code = http.StatusBadRequest, ErrCodeUsernameInvalid
|
||||
case errors.Is(err, ErrUsernameTaken):
|
||||
status, code = http.StatusConflict, ErrCodeUsernameTaken
|
||||
case errors.Is(err, ErrMailTaken):
|
||||
status, code = http.StatusConflict, ErrCodeMailTaken
|
||||
case errors.Is(err, ErrPasswordRejected):
|
||||
status, code = http.StatusBadRequest, ErrCodePasswordInvalid
|
||||
}
|
||||
if code == "" {
|
||||
logger.Error().Err(err).Str("username", f.Username).Msg("web registration failed")
|
||||
h.opt.Render.Error(w, r, status, ErrCodeProvision)
|
||||
return
|
||||
}
|
||||
f.ErrCode = code
|
||||
h.opt.Render.Register(w, r, status, f)
|
||||
return
|
||||
}
|
||||
logger.Info().Str("user_id", userID).Bool("pending", reg.RequireApproval).Msg("created account from web registration")
|
||||
|
||||
if reg.RequireApproval {
|
||||
err := h.opt.Pending.Add(PendingUser{
|
||||
UserID: userID,
|
||||
Username: f.Username,
|
||||
DisplayName: f.Username,
|
||||
Mail: f.Mail,
|
||||
Source: SourceWeb,
|
||||
RequestedAt: h.opt.Now().UTC(),
|
||||
})
|
||||
if err != nil {
|
||||
// The account is disabled, so it stays locked until an admin enables it.
|
||||
logger.Error().Err(err).Str("user_id", userID).Msg("could not record pending account")
|
||||
}
|
||||
h.opt.Render.Error(w, r, http.StatusOK, ErrCodeRegistrationSubmitted)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, f.LoginURL, http.StatusSeeOther)
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
package discord
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const testOrigin = "https://cloud.example.com"
|
||||
|
||||
type fakeWeb struct {
|
||||
id string
|
||||
created []WebUser
|
||||
enabled []bool
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeWeb) CreateWebUser(_ context.Context, u WebUser, enabled bool) (string, error) {
|
||||
if f.err != nil {
|
||||
return "", f.err
|
||||
}
|
||||
f.created = append(f.created, u)
|
||||
f.enabled = append(f.enabled, enabled)
|
||||
return f.id, nil
|
||||
}
|
||||
|
||||
func validRegisterForm() url.Values {
|
||||
return url.Values{
|
||||
"q": {"client_id=web&state=s1"},
|
||||
"username": {"carol"},
|
||||
"mail": {"carol@example.com"},
|
||||
"password": {"Secret-pass1"},
|
||||
"password_confirm": {"Secret-pass1"},
|
||||
}
|
||||
}
|
||||
|
||||
func (h *harness) postRegister(form url.Values, origin string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodPost, "/oauth2/discord/register", strings.NewReader(form.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
if origin != "" {
|
||||
req.Header.Set("Origin", origin)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
h.router.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
func (h *harness) openWeb(approval bool) {
|
||||
h.t.Helper()
|
||||
if err := h.reg.Save(RegistrationSettings{AllowRegistration: true, AllowWeb: true, AllowDiscord: true, RequireApproval: approval}); err != nil {
|
||||
h.t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebRegisterRejectedWhenWebDisabled(t *testing.T) {
|
||||
for name, s := range map[string]RegistrationSettings{
|
||||
"defaults": DefaultRegistrationSettings(),
|
||||
"discord only": {AllowRegistration: true, AllowDiscord: true, RequireApproval: true},
|
||||
"registration off": {AllowWeb: true},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
if err := h.reg.Save(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rec := h.do(http.MethodGet, "/oauth2/discord/register", nil); rec.Code != http.StatusForbidden || h.render.code != ErrCodeRegistrationClosed {
|
||||
t.Fatalf("GET status = %d code = %q", rec.Code, h.render.code)
|
||||
}
|
||||
h.render.code = ""
|
||||
if rec := h.postRegister(validRegisterForm(), testOrigin); rec.Code != http.StatusForbidden || h.render.code != ErrCodeRegistrationClosed {
|
||||
t.Fatalf("POST status = %d code = %q", rec.Code, h.render.code)
|
||||
}
|
||||
if len(h.web.created) != 0 {
|
||||
t.Fatal("account created while web registration is disabled")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebRegisterFormShown(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.openWeb(false)
|
||||
rec := h.do(http.MethodGet, "/oauth2/discord/register?client_id=web", nil)
|
||||
if rec.Code != http.StatusOK || h.render.register == nil {
|
||||
t.Fatalf("status = %d", rec.Code)
|
||||
}
|
||||
f := h.render.register
|
||||
if f.Action != "/oauth2/discord/register" || f.Query != "client_id=web" || f.LoginURL != "/signin/v1/identifier?client_id=web" {
|
||||
t.Errorf("form = %+v", f)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebRegisterCreatesEnabledAccount(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.openWeb(false)
|
||||
rec := h.postRegister(validRegisterForm(), testOrigin)
|
||||
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/signin/v1/identifier?client_id=web&state=s1" {
|
||||
t.Fatalf("status = %d location = %q", rec.Code, rec.Header().Get("Location"))
|
||||
}
|
||||
if len(h.web.created) != 1 || !h.web.enabled[0] {
|
||||
t.Fatalf("created = %+v enabled = %v", h.web.created, h.web.enabled)
|
||||
}
|
||||
if u := h.web.created[0]; u.Username != "carol" || u.Mail != "carol@example.com" || u.Password != "Secret-pass1" {
|
||||
t.Errorf("user = %+v", u)
|
||||
}
|
||||
if h.pending.IsPending(h.web.id) || h.sess.userID != "" {
|
||||
t.Error("no pending entry and no session expected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebRegisterWithApprovalIsPending(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.openWeb(true)
|
||||
rec := h.postRegister(validRegisterForm(), testOrigin)
|
||||
if rec.Code != http.StatusOK || h.render.code != ErrCodeRegistrationSubmitted {
|
||||
t.Fatalf("status = %d code = %q", rec.Code, h.render.code)
|
||||
}
|
||||
if len(h.web.enabled) != 1 || h.web.enabled[0] {
|
||||
t.Fatalf("account must be created disabled, got %v", h.web.enabled)
|
||||
}
|
||||
p, ok := h.pending.Get(h.web.id)
|
||||
if !ok || p.Source != SourceWeb || p.Username != "carol" || p.Mail != "carol@example.com" || p.RequestedAt.IsZero() {
|
||||
t.Fatalf("pending = %+v ok = %v", p, ok)
|
||||
}
|
||||
if h.sess.userID != "" {
|
||||
t.Error("no session may be issued for a pending account")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebRegisterValidation(t *testing.T) {
|
||||
tests := map[string]struct {
|
||||
field, value, code string
|
||||
}{
|
||||
"invalid username": {"username", "1x", ErrCodeUsernameInvalid},
|
||||
"invalid mail": {"mail", "not-a-mail", ErrCodeMailInvalid},
|
||||
"mail with name": {"mail", "Carol <carol@example.com>", ErrCodeMailInvalid},
|
||||
"short password": {"password", "short", ErrCodePasswordInvalid},
|
||||
"password mismatch": {"password_confirm", "Other-pass1", ErrCodePasswordMismatch},
|
||||
}
|
||||
for name, tt := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.openWeb(false)
|
||||
form := validRegisterForm()
|
||||
form.Set(tt.field, tt.value)
|
||||
if tt.field == "password" {
|
||||
form.Set("password_confirm", tt.value)
|
||||
}
|
||||
rec := h.postRegister(form, testOrigin)
|
||||
if rec.Code != http.StatusBadRequest || h.render.register == nil || h.render.register.ErrCode != tt.code {
|
||||
t.Fatalf("status = %d form = %+v", rec.Code, h.render.register)
|
||||
}
|
||||
if len(h.web.created) != 0 {
|
||||
t.Error("account created for invalid input")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebRegisterDirectoryErrors(t *testing.T) {
|
||||
tests := map[string]struct {
|
||||
err error
|
||||
status int
|
||||
code string
|
||||
}{
|
||||
"username taken": {ErrUsernameTaken, http.StatusConflict, ErrCodeUsernameTaken},
|
||||
"mail taken": {ErrMailTaken, http.StatusConflict, ErrCodeMailTaken},
|
||||
"password rejected": {ErrPasswordRejected, http.StatusBadRequest, ErrCodePasswordInvalid},
|
||||
}
|
||||
for name, tt := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.openWeb(false)
|
||||
h.web.err = tt.err
|
||||
rec := h.postRegister(validRegisterForm(), testOrigin)
|
||||
if rec.Code != tt.status || h.render.register == nil || h.render.register.ErrCode != tt.code {
|
||||
t.Fatalf("status = %d form = %+v", rec.Code, h.render.register)
|
||||
}
|
||||
if h.render.register.Username != "carol" || h.render.register.Mail != "carol@example.com" {
|
||||
t.Errorf("form lost the input: %+v", h.render.register)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
h := newHarness(t)
|
||||
h.openWeb(false)
|
||||
h.web.err = errors.New("graph down")
|
||||
if rec := h.postRegister(validRegisterForm(), testOrigin); rec.Code != http.StatusInternalServerError || h.render.code != ErrCodeProvision {
|
||||
t.Fatalf("status = %d code = %q", rec.Code, h.render.code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebRegisterRejectsCrossSitePost(t *testing.T) {
|
||||
for name, origin := range map[string]string{"other site": "https://evil.example.net", "no origin": ""} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.openWeb(false)
|
||||
if rec := h.postRegister(validRegisterForm(), origin); rec.Code != http.StatusForbidden || len(h.web.created) != 0 {
|
||||
t.Fatalf("status = %d created = %v", rec.Code, h.web.created)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebPendingUserCanLogInAfterApproval(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.openWeb(true)
|
||||
if rec := h.postRegister(validRegisterForm(), testOrigin); rec.Code != http.StatusOK {
|
||||
t.Fatalf("register status = %d", rec.Code)
|
||||
}
|
||||
|
||||
// lico rejects the disabled account; the guard reports pending approval.
|
||||
calls := 0
|
||||
if rec := postLogon(h.handler.GuardLogon(fakeLico(false, &calls)), "carol"); rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), ErrCodePendingApproval) {
|
||||
t.Fatalf("logon before approval: status = %d body = %s", rec.Code, rec.Body)
|
||||
}
|
||||
|
||||
if rec := h.do(http.MethodPost, "/oauth2/discord/admin/pending/"+h.web.id+"/approve", nil); rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("approve status = %d", rec.Code)
|
||||
}
|
||||
if len(h.accounts.approved) != 1 || h.accounts.approved[0] != h.web.id {
|
||||
t.Fatalf("approved = %v", h.accounts.approved)
|
||||
}
|
||||
|
||||
// The account is enabled: lico accepts the password and the response passes through.
|
||||
if rec := postLogon(h.handler.GuardLogon(fakeLico(true, &calls)), "carol"); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"success":true`) {
|
||||
t.Fatalf("logon after approval: status = %d body = %s", rec.Code, rec.Body)
|
||||
}
|
||||
// A wrong password is a normal failure again.
|
||||
if rec := postLogon(h.handler.GuardLogon(fakeLico(false, &calls)), "carol"); rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("wrong password after approval: status = %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGraphProvisionerCreateWebUser(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
dir := newFakeDirectory(graphUser("u9", "bob", "bob@example.com", "Bob", ""))
|
||||
p := GraphProvisioner{Dir: dir, Index: fakeIndex{}}
|
||||
|
||||
id, err := p.CreateWebUser(ctx, WebUser{Username: "carol", Mail: "carol@example.com", Password: "Secret-pass1"}, false)
|
||||
if err != nil || id != "new-user-id" {
|
||||
t.Fatalf("id = %q err = %v", id, err)
|
||||
}
|
||||
c := dir.created[0]
|
||||
if c.GetOnPremisesSamAccountName() != "carol" || c.GetMail() != "carol@example.com" || c.GetDisplayName() != "carol" {
|
||||
t.Errorf("created = %+v", c)
|
||||
}
|
||||
if c.GetAccountEnabled() {
|
||||
t.Error("account must be disabled")
|
||||
}
|
||||
if pp := c.GetPasswordProfile(); pp.GetPassword() != "Secret-pass1" {
|
||||
t.Error("password not set")
|
||||
}
|
||||
|
||||
if _, err := p.CreateWebUser(ctx, WebUser{Username: "Bob", Mail: "x@example.com", Password: "Secret-pass1"}, true); !errors.Is(err, ErrUsernameTaken) {
|
||||
t.Errorf("taken username: %v", err)
|
||||
}
|
||||
if _, err := p.CreateWebUser(ctx, WebUser{Username: "dave", Mail: "BOB@example.com", Password: "Secret-pass1"}, true); !errors.Is(err, ErrMailTaken) {
|
||||
t.Errorf("taken mail: %v", err)
|
||||
}
|
||||
if _, err := p.CreateWebUser(ctx, WebUser{Username: "1x", Mail: "e@example.com", Password: "Secret-pass1"}, true); !errors.Is(err, ErrUsernameInvalid) {
|
||||
t.Errorf("invalid username: %v", err)
|
||||
}
|
||||
|
||||
dir.createErr = &GraphStatusError{Status: http.StatusBadRequest, Body: "password must contain at least one special character"}
|
||||
if _, err := p.CreateWebUser(ctx, WebUser{Username: "erin", Mail: "erin@example.com", Password: "secretpass"}, true); !errors.Is(err, ErrPasswordRejected) {
|
||||
t.Errorf("password policy: %v", err)
|
||||
}
|
||||
dir.createErr = &GraphStatusError{Status: http.StatusInternalServerError, Body: "boom"}
|
||||
if _, err := p.CreateWebUser(ctx, WebUser{Username: "erin", Mail: "erin@example.com", Password: "Secret-pass1"}, true); err == nil || errors.Is(err, ErrPasswordRejected) || !strings.Contains(err.Error(), "graph returned 500") {
|
||||
t.Errorf("server error: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
package svc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
|
||||
"github.com/libregraph/lico/identifier"
|
||||
"github.com/libregraph/lico/managers"
|
||||
libregraph "github.com/owncloud/libre-graph-api-go"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/registry"
|
||||
"github.com/owncloud/ocis/v2/services/idp/pkg/config"
|
||||
"github.com/owncloud/ocis/v2/services/idp/pkg/discord"
|
||||
revactx "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
"go-micro.dev/v4/selector"
|
||||
"golang.org/x/text/language"
|
||||
)
|
||||
|
||||
const graphServiceName = "com.owncloud.web.graph"
|
||||
|
||||
// newDiscordHandler wires the Discord login into the idp. It returns an error
|
||||
// when a prerequisite is missing; the caller then disables the feature.
|
||||
func newDiscordHandler(idp *IDP, options Options, mgrs *managers.Managers, authorizePath string) (*discord.Handler, error) {
|
||||
cfg := options.Config
|
||||
|
||||
raw, ok := mgrs.Get("identifier")
|
||||
if !ok {
|
||||
return nil, errors.New("the identity manager does not expose a lico identifier")
|
||||
}
|
||||
ident, ok := raw.(*identifier.Identifier)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected identifier type %T", raw)
|
||||
}
|
||||
if cfg.TokenManager == nil || cfg.TokenManager.JWTSecret == "" {
|
||||
return nil, errors.New("jwt secret is not configured (OCIS_JWT_SECRET)")
|
||||
}
|
||||
if cfg.ServiceAccount.ServiceAccountID == "" || cfg.ServiceAccount.ServiceAccountSecret == "" {
|
||||
return nil, errors.New("service account is not configured (OCIS_SERVICE_ACCOUNT_ID / OCIS_SERVICE_ACCOUNT_SECRET)")
|
||||
}
|
||||
if cfg.Commons == nil || cfg.Commons.OcisURL == "" {
|
||||
return nil, errors.New("OCIS_URL is not configured")
|
||||
}
|
||||
if cfg.Reva == nil {
|
||||
return nil, errors.New("reva gateway is not configured")
|
||||
}
|
||||
|
||||
store, err := discord.NewStore(cfg.Discord.SettingsFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
registration, err := discord.NewRegistrationStore(filepath.Join(filepath.Dir(cfg.Discord.SettingsFile), "registration.json"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pending, err := discord.NewPendingStore(filepath.Join(filepath.Dir(cfg.Discord.SettingsFile), "pending.json"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
index, err := discord.NewLDAPIdentities(ldapIdentityConfig(cfg))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ldap identity lookup: %w", err)
|
||||
}
|
||||
|
||||
reg := registry.GetRegistry()
|
||||
gws, err := pool.GatewaySelector(
|
||||
cfg.Reva.Address,
|
||||
append(cfg.Reva.GetRevaOptions(), pool.WithRegistry(reg), pool.WithTracerProvider(options.TraceProvider))...,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("gateway selector: %w", err)
|
||||
}
|
||||
|
||||
admin, err := discord.NewJWTAdminAuthorizer(cfg.TokenManager.JWTSecret, discord.GatewayPermissionChecker{Selector: gws})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Derive the state signing key from the JWT secret so all idp instances
|
||||
// share it and restarts do not break logins in progress.
|
||||
key := sha256.Sum256([]byte("reverse-cloud/discord-state\x00" + cfg.TokenManager.JWTSecret))
|
||||
|
||||
prov := discord.GraphProvisioner{
|
||||
Dir: discord.GraphDirectory{
|
||||
Client: serviceGraphClient(cfg, gws, selector.NewSelector(selector.Registry(reg))),
|
||||
},
|
||||
Index: index,
|
||||
}
|
||||
|
||||
return discord.NewHandler(discord.Options{
|
||||
Store: store,
|
||||
Registration: registration,
|
||||
Pending: pending,
|
||||
Accounts: prov,
|
||||
WebAccounts: prov,
|
||||
API: discord.NewClient(),
|
||||
Provisioner: prov,
|
||||
Sessions: discord.LicoSessionIssuer{Identifier: ident, SubAttribute: cfg.Ldap.UUIDAttribute},
|
||||
Admin: admin,
|
||||
Users: admin,
|
||||
Render: newDiscordRenderer(idp),
|
||||
Logger: options.Logger,
|
||||
PublicURL: cfg.Commons.OcisURL,
|
||||
AuthorizePath: authorizePath,
|
||||
MustBeSignedIn: identifier.MustBeSignedIn,
|
||||
StateKey: key[:],
|
||||
})
|
||||
}
|
||||
|
||||
// ldapIdentityConfig returns the LDAP connection of the idp backend. Unlike
|
||||
// the login filter it does not exclude disabled users, so a disabled linked
|
||||
// account is still found and never gets a second account.
|
||||
func ldapIdentityConfig(cfg *config.Config) discord.LDAPConfig {
|
||||
l := cfg.Ldap
|
||||
filter := fmt.Sprintf("(objectclass=%s)", l.ObjectClass)
|
||||
if l.Filter != "" {
|
||||
filter = fmt.Sprintf("(&%s%s)", filter, l.Filter)
|
||||
}
|
||||
return discord.LDAPConfig{
|
||||
URI: l.URI,
|
||||
BindDN: l.BindDN,
|
||||
BindPassword: l.BindPassword,
|
||||
BaseDN: l.BaseDN,
|
||||
Scope: l.Scope,
|
||||
Filter: filter,
|
||||
UUIDAttribute: l.UUIDAttribute,
|
||||
CACert: l.TLSCACert,
|
||||
Insecure: cfg.IDP.Insecure,
|
||||
}
|
||||
}
|
||||
|
||||
// serviceGraphClient returns LibreGraph clients authenticated as the service account.
|
||||
func serviceGraphClient(cfg *config.Config, gws pool.Selectable[gateway.GatewayAPIClient], sel selector.Selector) discord.GraphClientFunc {
|
||||
httpClient := &http.Client{Timeout: 15 * time.Second}
|
||||
return func(ctx context.Context) (*libregraph.APIClient, error) {
|
||||
gwc, err := gws.Next()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tok, err := utils.GetServiceUserToken(ctx, gwc, cfg.ServiceAccount.ServiceAccountID, cfg.ServiceAccount.ServiceAccountSecret)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("authenticate service account: %w", err)
|
||||
}
|
||||
next, err := sel.Select(graphServiceName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("select graph service: %w", err)
|
||||
}
|
||||
node, err := next()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("select graph node: %w", err)
|
||||
}
|
||||
scheme := node.Metadata["protocol"]
|
||||
if node.Metadata["use_tls"] == "true" {
|
||||
scheme = "https"
|
||||
}
|
||||
if scheme == "" {
|
||||
scheme = "http"
|
||||
}
|
||||
lg := libregraph.NewConfiguration()
|
||||
lg.Servers = libregraph.ServerConfigurations{{URL: fmt.Sprintf("%s://%s/graph", scheme, node.Address)}}
|
||||
lg.DefaultHeader = map[string]string{revactx.TokenHeader: tok}
|
||||
lg.HTTPClient = httpClient
|
||||
return libregraph.NewAPIClient(lg), nil
|
||||
}
|
||||
}
|
||||
|
||||
var discordContinueTpl = template.Must(template.New("discord-continue").Parse(`<!DOCTYPE html>
|
||||
<html lang="{{.Lang}}">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta http-equiv="refresh" content="0;url={{.Target}}">
|
||||
<title>{{.Title}}</title>
|
||||
<link rel="icon" href="{{.PathPrefix}}/static/favicon.ico">
|
||||
<link rel="stylesheet" href="{{.PathPrefix}}/static/theme.css">
|
||||
</head>
|
||||
<body class="oc-login-bg">
|
||||
<main>
|
||||
<div class="oc-login-form">
|
||||
<img class="oc-logo" src="{{.LogoURL}}" alt="ownCloud">
|
||||
<p class="oc-message"><a href="{{.Target}}">{{.Message}}</a></p>
|
||||
</div>
|
||||
</main>
|
||||
<script nonce="{{.Nonce}}">window.location.replace({{.Target}});</script>
|
||||
</body>
|
||||
</html>
|
||||
`))
|
||||
|
||||
type discordContinueData struct {
|
||||
basePageData
|
||||
Target string
|
||||
Message string
|
||||
}
|
||||
|
||||
// discordRenderer renders the Discord flow pages with the idp login layout.
|
||||
type discordRenderer struct {
|
||||
idp *IDP
|
||||
errTpl *template.Template
|
||||
signupTpl *template.Template
|
||||
registerTpl *template.Template
|
||||
}
|
||||
|
||||
func newDiscordRenderer(idp *IDP) discordRenderer {
|
||||
return discordRenderer{
|
||||
idp: idp,
|
||||
errTpl: idp.mustParseTemplate("/identifier/loginerror.html", "Could not load loginerror template"),
|
||||
signupTpl: idp.mustParseTemplate("/identifier/discord_signup.html", "Could not load discord signup template"),
|
||||
registerTpl: idp.mustParseTemplate("/identifier/discord_register.html", "Could not load registration template"),
|
||||
}
|
||||
}
|
||||
|
||||
type discordSignupData struct {
|
||||
basePageData
|
||||
discord.SignupForm
|
||||
Intro, LabelUsername, Hint, Button, Error string
|
||||
}
|
||||
|
||||
// Signup implements discord.Renderer.
|
||||
func (d discordRenderer) Signup(w http.ResponseWriter, r *http.Request, status int, f discord.SignupForm) {
|
||||
base := d.page(r, "Sign in - ownCloud", "Login")
|
||||
data := discordSignupData{
|
||||
basePageData: base,
|
||||
SignupForm: f,
|
||||
Intro: localized(r,
|
||||
fmt.Sprintf("Signed in to Discord as %s. Choose the username of your new account.", f.DisplayName),
|
||||
fmt.Sprintf("Discord の %s としてログインしました。新しいアカウントのユーザー名を決めてください。", f.DisplayName)),
|
||||
LabelUsername: localized(r, "Username", "ユーザー名"),
|
||||
Hint: localized(r,
|
||||
"3 to 32 characters. Start with a letter or _, then use letters, digits, '.', '_' or '-'.",
|
||||
"3〜32 文字。先頭は英字か _ で、英数字と . _ - が使えます。"),
|
||||
Button: localized(r, "Create account", "アカウントを作成"),
|
||||
}
|
||||
if f.ErrCode != "" {
|
||||
data.Error = discordErrorMessage(r, f.ErrCode)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := d.signupTpl.Execute(&buf, data); err != nil {
|
||||
http.Error(w, "template error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
writeSecureHTMLStatus(w, buf.Bytes(), base.Nonce, status)
|
||||
}
|
||||
|
||||
func (d discordRenderer) page(r *http.Request, title, headline string) basePageData {
|
||||
base, _ := d.idp.basePage(r, title, headline)
|
||||
if prefersJapanese(r) {
|
||||
base.Lang = "ja"
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
// Error implements discord.Renderer.
|
||||
func (d discordRenderer) Error(w http.ResponseWriter, r *http.Request, status int, code string) {
|
||||
base := d.page(r, "Login Error - ownCloud", "Login Error")
|
||||
var buf bytes.Buffer
|
||||
if err := d.errTpl.Execute(&buf, pageData{basePageData: base, Message: discordErrorMessage(r, code)}); err != nil {
|
||||
http.Error(w, "template error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
writeSecureHTMLStatus(w, buf.Bytes(), base.Nonce, status)
|
||||
}
|
||||
|
||||
// Continue implements discord.Renderer.
|
||||
func (d discordRenderer) Continue(w http.ResponseWriter, r *http.Request, target string) {
|
||||
base := d.page(r, "Sign in - ownCloud", "Login")
|
||||
var buf bytes.Buffer
|
||||
data := discordContinueData{
|
||||
basePageData: base,
|
||||
Target: target,
|
||||
Message: localized(r, "Signing in… Continue", "ログインしています… 続行"),
|
||||
}
|
||||
if err := discordContinueTpl.Execute(&buf, data); err != nil {
|
||||
http.Error(w, "template error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
writeSecureHTMLStatus(w, buf.Bytes(), base.Nonce, http.StatusOK)
|
||||
}
|
||||
|
||||
var discordMessages = map[string][2]string{ // {en, ja}
|
||||
discord.ErrCodeNotMember: {
|
||||
"You cannot access this service because you have not joined the required Discord server. Please join the server first.",
|
||||
"指定の Discord サーバーに参加していないためアクセスできません。先にサーバーへ参加してください。",
|
||||
},
|
||||
discord.ErrCodeDisabled: {
|
||||
"Discord login is not available.",
|
||||
"Discord ログインは現在利用できません。",
|
||||
},
|
||||
discord.ErrCodeInvalidState: {
|
||||
"The login request is invalid. Please start the login again.",
|
||||
"ログイン要求が無効です。もう一度ログインしてください。",
|
||||
},
|
||||
discord.ErrCodeExpired: {
|
||||
"The login request has expired. Please start the login again.",
|
||||
"ログイン要求の有効期限が切れました。もう一度ログインしてください。",
|
||||
},
|
||||
discord.ErrCodeInvalidCode: {
|
||||
"Discord did not confirm the login. Please try again.",
|
||||
"Discord でのログインを確認できませんでした。もう一度お試しください。",
|
||||
},
|
||||
discord.ErrCodeCancelled: {
|
||||
"The Discord authorization was cancelled.",
|
||||
"Discord での認可がキャンセルされました。",
|
||||
},
|
||||
discord.ErrCodeUpstream: {
|
||||
"Discord could not be reached. Please try again later.",
|
||||
"Discord に接続できませんでした。しばらくしてからもう一度お試しください。",
|
||||
},
|
||||
discord.ErrCodeProvision: {
|
||||
"Your account could not be set up. Please contact an administrator.",
|
||||
"アカウントを準備できませんでした。管理者に連絡してください。",
|
||||
},
|
||||
discord.ErrCodeServer: {
|
||||
"Login failed because of a server error. Please try again.",
|
||||
"サーバーエラーのためログインできませんでした。もう一度お試しください。",
|
||||
},
|
||||
discord.ErrCodeUsernameInvalid: {
|
||||
"This username cannot be used. Please follow the rules below the field.",
|
||||
"このユーザー名は使えません。入力欄の下の条件を確認してください。",
|
||||
},
|
||||
discord.ErrCodeUsernameTaken: {
|
||||
"This username is already taken. Please choose another one.",
|
||||
"このユーザー名は既に使われています。別のユーザー名を選んでください。",
|
||||
},
|
||||
discord.ErrCodeRegistrationClosed: {
|
||||
"New registrations are currently not accepted.",
|
||||
"現在、新規登録は受け付けていません。",
|
||||
},
|
||||
discord.ErrCodePendingApproval: {
|
||||
"Your account is waiting for an administrator's approval.",
|
||||
"現在、管理者の承認待ちです。",
|
||||
},
|
||||
discord.ErrCodeRegistrationSubmitted: {
|
||||
"Your registration request has been received. Please wait for an administrator's approval.",
|
||||
"アカウント登録申請を受け付けました。管理者の承認をお待ちください。",
|
||||
},
|
||||
discord.ErrCodeMailInvalid: {
|
||||
"Please enter a valid email address.",
|
||||
"有効なメールアドレスを入力してください。",
|
||||
},
|
||||
discord.ErrCodeMailTaken: {
|
||||
"This email address is already used by another account.",
|
||||
"このメールアドレスは既に別のアカウントで使われています。",
|
||||
},
|
||||
discord.ErrCodePasswordInvalid: {
|
||||
"The password does not meet the requirements.",
|
||||
"パスワードが条件を満たしていません。",
|
||||
},
|
||||
discord.ErrCodePasswordMismatch: {
|
||||
"The passwords do not match.",
|
||||
"パスワードが一致しません。",
|
||||
},
|
||||
}
|
||||
|
||||
func discordErrorMessage(r *http.Request, code string) string {
|
||||
m, ok := discordMessages[code]
|
||||
if !ok {
|
||||
m = discordMessages[discord.ErrCodeServer]
|
||||
}
|
||||
return localized(r, m[0], m[1])
|
||||
}
|
||||
|
||||
var jaMatcher = language.NewMatcher([]language.Tag{language.English, language.Japanese})
|
||||
|
||||
func prefersJapanese(r *http.Request) bool {
|
||||
tag, _ := language.MatchStrings(jaMatcher, r.Header.Get("Accept-Language"))
|
||||
base, _ := tag.Base()
|
||||
return base.String() == "ja"
|
||||
}
|
||||
|
||||
func localized(r *http.Request, en, ja string) string {
|
||||
if prefersJapanese(r) {
|
||||
return ja
|
||||
}
|
||||
return en
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package svc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
|
||||
"github.com/owncloud/ocis/v2/services/idp/pkg/discord"
|
||||
)
|
||||
|
||||
type discordRegisterData struct {
|
||||
basePageData
|
||||
discord.RegisterForm
|
||||
Intro, LabelUsername, HintUsername, LabelMail string
|
||||
LabelPassword, HintPassword, LabelConfirm string
|
||||
Button, BackLabel, Error, ErrField string
|
||||
}
|
||||
|
||||
// registerErrField returns the form field an error code belongs to.
|
||||
func registerErrField(code string) string {
|
||||
switch code {
|
||||
case discord.ErrCodeUsernameInvalid, discord.ErrCodeUsernameTaken:
|
||||
return "username"
|
||||
case discord.ErrCodeMailInvalid, discord.ErrCodeMailTaken:
|
||||
return "mail"
|
||||
case discord.ErrCodePasswordInvalid, discord.ErrCodePasswordMismatch:
|
||||
return "password"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Register implements discord.Renderer.
|
||||
func (d discordRenderer) Register(w http.ResponseWriter, r *http.Request, status int, f discord.RegisterForm) {
|
||||
base := d.page(r, "Create account - ownCloud", "Create account")
|
||||
data := discordRegisterData{
|
||||
basePageData: base,
|
||||
RegisterForm: f,
|
||||
Intro: localized(r, "Create a new account.", "新しいアカウントを作成します。"),
|
||||
LabelUsername: localized(r, "Username", "ユーザー名"),
|
||||
HintUsername: localized(r,
|
||||
"3 to 32 characters. Start with a letter or _, then use letters, digits, '.', '_' or '-'.",
|
||||
"3〜32 文字。先頭は英字か _ で、英数字と . _ - が使えます。"),
|
||||
LabelMail: localized(r, "Email", "メールアドレス"),
|
||||
LabelPassword: localized(r, "Password", "パスワード"),
|
||||
HintPassword: localized(r,
|
||||
"At least 8 characters with upper and lower case letters, a digit and a symbol.",
|
||||
"8 文字以上で、英大文字・英小文字・数字・記号を含めてください。"),
|
||||
LabelConfirm: localized(r, "Confirm password", "パスワード(確認)"),
|
||||
Button: localized(r, "Create account", "アカウントを作成"),
|
||||
BackLabel: localized(r, "Back to login", "ログイン画面に戻る"),
|
||||
}
|
||||
if f.ErrCode != "" {
|
||||
data.Error = discordErrorMessage(r, f.ErrCode)
|
||||
data.ErrField = registerErrField(f.ErrCode)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := d.registerTpl.Execute(&buf, data); err != nil {
|
||||
http.Error(w, "template error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
writeSecureHTMLStatus(w, buf.Bytes(), base.Nonce, status)
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package svc
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/owncloud/ocis/v2/services/idp/pkg/discord"
|
||||
)
|
||||
|
||||
func TestDiscordErrorPageNotMember(t *testing.T) {
|
||||
svc, _ := newTestService(t, nil)
|
||||
r := newDiscordRenderer(svc.(*IDP))
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/oauth2/discord/callback", nil)
|
||||
req.Header.Set("Accept-Language", "ja,en;q=0.5")
|
||||
rec := httptest.NewRecorder()
|
||||
r.Error(rec, req, http.StatusForbidden, discord.ErrCodeNotMember)
|
||||
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("status = %d, want 403", rec.Code)
|
||||
}
|
||||
body := rec.Body.String()
|
||||
if !strings.Contains(body, "指定の Discord サーバーに参加していないためアクセスできません。先にサーバーへ参加してください。") {
|
||||
t.Errorf("missing japanese message: %s", body)
|
||||
}
|
||||
if !strings.Contains(body, `class="oc-message"`) || !strings.Contains(body, `<html lang="ja">`) {
|
||||
t.Error("error page does not use the login layout")
|
||||
}
|
||||
if rec.Header().Get("Content-Security-Policy") == "" {
|
||||
t.Error("missing security headers")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscordErrorPageEnglishAndUnknownCode(t *testing.T) {
|
||||
svc, _ := newTestService(t, nil)
|
||||
r := newDiscordRenderer(svc.(*IDP))
|
||||
rec := httptest.NewRecorder()
|
||||
r.Error(rec, httptest.NewRequest(http.MethodGet, "/", nil), http.StatusInternalServerError, "unknown")
|
||||
if !strings.Contains(rec.Body.String(), "Login failed because of a server error") {
|
||||
t.Errorf("unexpected body %s", rec.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscordContinuePageEscapesTarget(t *testing.T) {
|
||||
svc, _ := newTestService(t, nil)
|
||||
r := newDiscordRenderer(svc.(*IDP))
|
||||
rec := httptest.NewRecorder()
|
||||
target := "/signin/v1/identifier/_/authorize?client_id=web&state=a\"<b>"
|
||||
r.Continue(rec, httptest.NewRequest(http.MethodGet, "/", nil), target)
|
||||
body := rec.Body.String()
|
||||
if strings.Contains(body, `a"<b>`) {
|
||||
t.Fatalf("target is not escaped: %s", body)
|
||||
}
|
||||
if !strings.Contains(body, "window.location.replace(") {
|
||||
t.Error("missing redirect script")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscordSignupPage(t *testing.T) {
|
||||
svc, _ := newTestService(t, nil)
|
||||
r := newDiscordRenderer(svc.(*IDP))
|
||||
req := httptest.NewRequest(http.MethodGet, "/oauth2/discord/callback", nil)
|
||||
req.Header.Set("Accept-Language", "ja")
|
||||
rec := httptest.NewRecorder()
|
||||
r.Signup(rec, req, http.StatusConflict, discord.SignupForm{
|
||||
Action: "/oauth2/discord/signup",
|
||||
Token: "tok",
|
||||
Username: `bob"<x>`,
|
||||
DisplayName: "<b>Alice</b>",
|
||||
ErrCode: discord.ErrCodeUsernameTaken,
|
||||
})
|
||||
if rec.Code != http.StatusConflict {
|
||||
t.Fatalf("status = %d, want 409", rec.Code)
|
||||
}
|
||||
body := rec.Body.String()
|
||||
for _, s := range []string{
|
||||
`action="/oauth2/discord/signup"`,
|
||||
`name="token" value="tok"`,
|
||||
`id="discord-signup-username"`,
|
||||
"このユーザー名は既に使われています。",
|
||||
"アカウントを作成",
|
||||
} {
|
||||
if !strings.Contains(body, s) {
|
||||
t.Errorf("missing %q", s)
|
||||
}
|
||||
}
|
||||
if strings.Contains(body, `bob"<x>`) || strings.Contains(body, "<b>Alice</b>") {
|
||||
t.Error("user input is not escaped")
|
||||
}
|
||||
if rec.Header().Get("Content-Security-Policy") == "" {
|
||||
t.Error("missing security headers")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIndexHidesDiscordButtonWhenUnavailable(t *testing.T) {
|
||||
_, srv := newTestService(t, nil)
|
||||
_, body, _ := getPage(t, srv, "/signin/v1/identifier", "")
|
||||
if strings.Contains(body, "discord-login-btn") {
|
||||
t.Error("discord button must not be rendered when discord login is unavailable")
|
||||
}
|
||||
// the existing form is unchanged
|
||||
for _, s := range []string{`id="login-form"`, `id="submit-btn"`, `class="oc-button-primary"`} {
|
||||
if !strings.Contains(body, s) {
|
||||
t.Errorf("missing %q", s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIndexTemplateRendersDiscordButton(t *testing.T) {
|
||||
svc, _ := newTestService(t, nil)
|
||||
idp := svc.(*IDP)
|
||||
tpl := idp.mustParseTemplate("/identifier/index.html", "template")
|
||||
req := httptest.NewRequest(http.MethodGet, "/signin/v1/identifier?client_id=web", nil)
|
||||
base, _ := idp.basePage(req, "Sign in - ownCloud", "Login")
|
||||
rec := httptest.NewRecorder()
|
||||
idp.renderPage(rec, tpl, base.Nonce, indexData{
|
||||
basePageData: base,
|
||||
DiscordLoginURL: "/oauth2/discord/login?client_id=web",
|
||||
DiscordLabel: "Log in with Discord",
|
||||
OrLabel: "or",
|
||||
})
|
||||
body := rec.Body.String()
|
||||
for _, s := range []string{
|
||||
`id="discord-login-btn"`,
|
||||
`class="oc-button-primary oc-button-discord"`,
|
||||
`href="/oauth2/discord/login?client_id=web"`,
|
||||
"Log in with Discord",
|
||||
} {
|
||||
if !strings.Contains(body, s) {
|
||||
t.Errorf("missing %q", s)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package svc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/owncloud/ocis/v2/services/idp/pkg/backends/ldapverified"
|
||||
"github.com/owncloud/ocis/v2/services/idp/pkg/config"
|
||||
"github.com/owncloud/ocis/v2/services/idp/pkg/discord"
|
||||
)
|
||||
|
||||
// registerLDAPIdentityManager registers the ldap identity manager that
|
||||
// reports email_verified=true for accounts linked to Discord.
|
||||
func registerLDAPIdentityManager(cfg *config.Config) error {
|
||||
checker, err := discord.NewLDAPIdentities(ldapIdentityConfig(cfg))
|
||||
if err != nil {
|
||||
return fmt.Errorf("ldap identity lookup: %w", err)
|
||||
}
|
||||
return ldapverified.Register(checker, discord.IdentityIssuer)
|
||||
}
|
||||
@@ -32,6 +32,7 @@ import (
|
||||
"github.com/owncloud/ocis/v2/services/idp/pkg/assets"
|
||||
cs3BackendSupport "github.com/owncloud/ocis/v2/services/idp/pkg/backends/cs3/bootstrap"
|
||||
"github.com/owncloud/ocis/v2/services/idp/pkg/config"
|
||||
"github.com/owncloud/ocis/v2/services/idp/pkg/discord"
|
||||
"github.com/owncloud/ocis/v2/services/idp/pkg/middleware"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
"golang.org/x/text/language"
|
||||
@@ -81,7 +82,10 @@ func NewService(opts ...Option) Service {
|
||||
options.Config.Ldap.TLSCACert = ""
|
||||
}
|
||||
|
||||
ldapBackendSupport.MustRegister()
|
||||
if err := registerLDAPIdentityManager(options.Config); err != nil {
|
||||
logger.Warn().Err(err).Msg("email_verified for discord accounts is disabled")
|
||||
ldapBackendSupport.MustRegister()
|
||||
}
|
||||
if err := initLicoInternalLDAPEnvVars(&options.Config.Ldap); err != nil {
|
||||
logger.Fatal().Err(err).Msg("could not initialize ldap env vars")
|
||||
}
|
||||
@@ -150,6 +154,18 @@ func NewService(opts ...Option) Service {
|
||||
passwordResetURI: safePasswordResetURI(options.Config.Service.PasswordResetURI),
|
||||
}
|
||||
|
||||
if options.Config.IDP.IdentityManager != "ldap" {
|
||||
logger.Error().Str("identity_manager", options.Config.IDP.IdentityManager).Msg("discord login is disabled: requires IDP_IDENTITY_MANAGER=ldap")
|
||||
} else {
|
||||
dh, err := newDiscordHandler(svc, options, managers, bs.Config().AuthorizationEndpointURI.Path)
|
||||
if err != nil {
|
||||
// Error level: the default log level is error, a warning would be invisible.
|
||||
logger.Error().Err(err).Msg("discord login is disabled")
|
||||
} else {
|
||||
svc.discord = dh
|
||||
}
|
||||
}
|
||||
|
||||
svc.initMux(ctx, routes, handlers, options)
|
||||
|
||||
return svc
|
||||
@@ -279,6 +295,7 @@ type IDP struct {
|
||||
passwordResetURI template.URL
|
||||
logoURL string
|
||||
logoOnce sync.Once
|
||||
discord *discord.Handler
|
||||
}
|
||||
|
||||
// initMux initializes the internal idp gorilla mux and mounts it in to an ocis chi-router
|
||||
@@ -311,11 +328,18 @@ func (idp *IDP) initMux(ctx context.Context, r []server.WithRoutes, h http.Handl
|
||||
r.Get("/signin/v1/consent", idp.Consent())
|
||||
r.Get("/signin/v1/loginerror", idp.LoginError())
|
||||
r.Get("/signin/v1/chooseaccount", idp.Chooseaccount())
|
||||
if idp.discord != nil {
|
||||
idp.discord.Mount(r)
|
||||
}
|
||||
})
|
||||
|
||||
idp.mux.Group(func(r chi.Router) {
|
||||
// routes handled by lico
|
||||
r.Use(middleware.CheckRedirect(options.Config, options.Logger))
|
||||
if idp.discord != nil {
|
||||
// Reports pending approval instead of a generic login failure.
|
||||
r.Post("/signin/v1/identifier/_/logon", idp.discord.GuardLogon(gm).ServeHTTP)
|
||||
}
|
||||
r.Mount("/", gm)
|
||||
})
|
||||
|
||||
@@ -341,8 +365,11 @@ type indexData struct {
|
||||
LabelUsername, LabelPassword string
|
||||
ButtonSignIn, ButtonSigningIn string
|
||||
ErrRequired, ErrInvalid, ErrFailed, ErrDefault string
|
||||
ErrPending string
|
||||
PasswordResetURI template.URL
|
||||
ResetLabel string
|
||||
DiscordLoginURL, DiscordLabel, OrLabel string
|
||||
RegisterURL, RegisterLabel string
|
||||
}
|
||||
|
||||
type pageData struct {
|
||||
@@ -433,9 +460,29 @@ func (idp *IDP) Index() http.HandlerFunc {
|
||||
ErrInvalid: t.Get("Login failed. Invalid username or password."),
|
||||
ErrFailed: t.Get("Login failed. Invalid username or password."),
|
||||
ErrDefault: t.Get("Login failed. Invalid username or password."),
|
||||
ErrPending: localized(r, "Your account is waiting for an administrator's approval.", "現在、管理者の承認待ちです。"),
|
||||
PasswordResetURI: idp.passwordResetURI,
|
||||
ResetLabel: t.Get("Reset password"),
|
||||
}
|
||||
if idp.discord != nil {
|
||||
query := ""
|
||||
if r.URL.RawQuery != "" {
|
||||
query = "?" + r.URL.RawQuery
|
||||
}
|
||||
pub := idp.discord.PublicRegistration()
|
||||
if pub.DiscordLogin {
|
||||
data.DiscordLoginURL = discord.RoutePrefix() + "/login" + query
|
||||
data.DiscordLabel = localized(r, "Log in with Discord", "Discord でログイン")
|
||||
if pub.Discord {
|
||||
data.DiscordLabel = localized(r, "Log in / Sign up with Discord", "Discord でログイン / 登録")
|
||||
}
|
||||
data.OrLabel = localized(r, "or", "または")
|
||||
}
|
||||
if pub.Web && len(r.URL.RawQuery) <= 4096 {
|
||||
data.RegisterURL = discord.RoutePrefix() + "/register" + query
|
||||
data.RegisterLabel = localized(r, "Create account", "アカウント作成")
|
||||
}
|
||||
}
|
||||
idp.renderPage(w, tpl, base.Nonce, data)
|
||||
}
|
||||
}
|
||||
@@ -597,6 +644,10 @@ type themeJSON struct {
|
||||
}
|
||||
|
||||
func writeSecureHTML(w http.ResponseWriter, body []byte, nonce string) {
|
||||
writeSecureHTMLStatus(w, body, nonce, http.StatusOK)
|
||||
}
|
||||
|
||||
func writeSecureHTMLStatus(w http.ResponseWriter, body []byte, nonce string, status int) {
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", "text/html; charset=utf-8")
|
||||
h.Set("Content-Security-Policy", fmt.Sprintf(
|
||||
@@ -607,6 +658,6 @@ func writeSecureHTML(w http.ResponseWriter, body []byte, nonce string) {
|
||||
h.Set("X-Content-Type-Options", "nosniff")
|
||||
h.Set("Referrer-Policy", "origin")
|
||||
h.Set("Cache-Control", "no-store, no-cache, must-revalidate")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.WriteHeader(status)
|
||||
w.Write(body) //nolint:errcheck
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
[main]
|
||||
host = https://www.transifex.com
|
||||
|
||||
[o:owncloud-org:p:owncloud-web:r:ocis-notifications]
|
||||
file_filter = locale/<lang>/LC_MESSAGES/notifications.po
|
||||
minimum_perc = 75
|
||||
resource_name = ocis-notifications
|
||||
source_file = notifications.pot
|
||||
source_lang = en
|
||||
type = PO
|
||||
@@ -5,13 +5,16 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"time"
|
||||
|
||||
"github.com/owncloud/reva/v2/pkg/events"
|
||||
"github.com/owncloud/reva/v2/pkg/events/stream"
|
||||
"github.com/owncloud/reva/v2/pkg/store"
|
||||
"github.com/urfave/cli/v2"
|
||||
microstore "go-micro.dev/v4/store"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/generators"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/natsconsumer"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/runner"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/tracing"
|
||||
"github.com/owncloud/ocis/v2/services/postprocessing/pkg/config"
|
||||
@@ -73,6 +76,27 @@ func Server(cfg *config.Config) *cli.Command {
|
||||
return err
|
||||
}
|
||||
|
||||
// The consumer exists now (NewPostprocessingService subscribed), so its
|
||||
// server-side settings can be adjusted without breaking later restarts.
|
||||
go func() {
|
||||
ev := cfg.Postprocessing.Events
|
||||
err := natsconsumer.Ensure(ctx, logger, natsconsumer.Connection{
|
||||
Endpoint: ev.Endpoint,
|
||||
Name: cfg.Service.Name + "-consumer-config",
|
||||
EnableTLS: ev.EnableTLS,
|
||||
TLSInsecure: ev.TLSInsecure,
|
||||
TLSRootCACertificate: ev.TLSRootCACertificate,
|
||||
AuthUsername: ev.AuthUsername,
|
||||
AuthPassword: ev.AuthPassword,
|
||||
}, events.MainQueueName, "postprocessing", natsconsumer.Settings{
|
||||
AckWait: cfg.Postprocessing.AckWait,
|
||||
MaxDeliver: cfg.Postprocessing.MaxDelivery,
|
||||
}, 5*time.Second)
|
||||
if err != nil {
|
||||
logger.Error().Err(err).Msg("could not apply NATS consumer settings")
|
||||
}
|
||||
}()
|
||||
|
||||
gr.Add(runner.New(cfg.Service.Name+".svc", func() error {
|
||||
return svc.Run()
|
||||
}, func() {
|
||||
|
||||
@@ -26,7 +26,11 @@ type Config struct {
|
||||
// Postprocessing defines the config options for the postprocessing service.
|
||||
type Postprocessing struct {
|
||||
Events Events `yaml:"events"`
|
||||
Workers int `yaml:"workers" env:"POSTPROCESSING_WORKERS" desc:"The number of concurrent go routines that fetch events from the event queue." introductionVersion:"6.7"`
|
||||
Workers int `yaml:"workers" env:"POSTPROCESSING_WORKERS;POSTPROCESSING_CONCURRENCY" desc:"The number of concurrent go routines that fetch events from the event queue. POSTPROCESSING_CONCURRENCY is an alias and takes precedence when both are set." introductionVersion:"6.7"`
|
||||
|
||||
AckWait time.Duration `yaml:"ack_wait" env:"POSTPROCESSING_ACK_WAIT" desc:"How long the NATS JetStream server waits for an acknowledgement before it redelivers an event to the postprocessing consumer. The value is written to the durable consumer on the server at startup. Set to 0 to keep the current server value. See the Environment Variable Types description for more details." introductionVersion:"8.3.0"`
|
||||
MaxDelivery int `yaml:"max_delivery" env:"POSTPROCESSING_MAX_DELIVERY" desc:"Maximum number of delivery attempts of an event to the postprocessing consumer. Events exceeding it are no longer redelivered. -1 means unlimited, 0 keeps the current server value." introductionVersion:"8.3.0"`
|
||||
DedupWindow time.Duration `yaml:"dedup_window" env:"POSTPROCESSING_DEDUP_WINDOW" desc:"How long event IDs are remembered to drop redelivered duplicates. Should be at least ack_wait multiplied by max_delivery. Set to 0 to disable deduplication. See the Environment Variable Types description for more details." introductionVersion:"8.3.0"`
|
||||
|
||||
Steps []string `yaml:"steps" env:"POSTPROCESSING_STEPS" desc:"A list of postprocessing steps processed in order of their appearance. Currently supported values by the system are: 'virusscan', 'policies' and 'delay'. Custom steps are allowed. See the documentation for instructions. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
Delayprocessing time.Duration `yaml:"delayprocessing" env:"POSTPROCESSING_DELAY" desc:"After uploading a file but before making it available for download, a delay step can be added. Intended for developing purposes only. If a duration is set but the keyword 'delay' is not explicitely added to 'POSTPROCESSING_STEPS', the delay step will be processed as last step. In such a case, a log entry will be written on service startup to remind the admin about that situation. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
@@ -57,11 +61,11 @@ type Debug struct {
|
||||
|
||||
// Store configures the store to use
|
||||
type Store struct {
|
||||
Store string `yaml:"store" env:"OCIS_PERSISTENT_STORE;POSTPROCESSING_STORE" desc:"The type of the store. Supported values are: 'memory', 'redis-sentinel', 'nats-js-kv', 'noop'. See the text description for details." introductionVersion:"pre5.0"`
|
||||
Nodes []string `yaml:"nodes" env:"OCIS_PERSISTENT_STORE_NODES;POSTPROCESSING_STORE_NODES" desc:"A list of nodes to access the configured store. This has no effect when 'memory' store is configured. Note that the behaviour how nodes are used is dependent on the library of the configured store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
Database string `yaml:"database" env:"POSTPROCESSING_STORE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"pre5.0"`
|
||||
Table string `yaml:"table" env:"POSTPROCESSING_STORE_TABLE" desc:"The database table the store should use." introductionVersion:"pre5.0"`
|
||||
TTL time.Duration `yaml:"ttl" env:"OCIS_PERSISTENT_STORE_TTL;POSTPROCESSING_STORE_TTL" desc:"Time to live for events in the store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
Store string `yaml:"store" env:"OCIS_PERSISTENT_STORE;POSTPROCESSING_STORE" desc:"The type of the store. Supported values are: 'memory', 'redis-sentinel', 'nats-js-kv', 'noop'. See the text description for details." introductionVersion:"pre5.0"`
|
||||
Nodes []string `yaml:"nodes" env:"OCIS_PERSISTENT_STORE_NODES;POSTPROCESSING_STORE_NODES" desc:"A list of nodes to access the configured store. This has no effect when 'memory' store is configured. Note that the behaviour how nodes are used is dependent on the library of the configured store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
Database string `yaml:"database" env:"POSTPROCESSING_STORE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"pre5.0"`
|
||||
Table string `yaml:"table" env:"POSTPROCESSING_STORE_TABLE" desc:"The database table the store should use." introductionVersion:"pre5.0"`
|
||||
TTL time.Duration `yaml:"ttl" env:"OCIS_PERSISTENT_STORE_TTL;POSTPROCESSING_STORE_TTL" desc:"Time to live for events in the store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
AuthUsername string `yaml:"username" env:"OCIS_PERSISTENT_STORE_AUTH_USERNAME;POSTPROCESSING_STORE_AUTH_USERNAME" desc:"The username to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
AuthPassword string `yaml:"password" env:"OCIS_PERSISTENT_STORE_AUTH_PASSWORD;POSTPROCESSING_STORE_AUTH_PASSWORD" desc:"The password to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
EnableTLS bool `yaml:"enable_tls" env:"OCIS_PERSISTENT_STORE_ENABLE_TLS;POSTPROCESSING_STORE_ENABLE_TLS" desc:"Activate TLS for the connection to the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
|
||||
@@ -32,6 +32,9 @@ func DefaultConfig() *config.Config {
|
||||
Cluster: "ocis-cluster",
|
||||
},
|
||||
Workers: 3,
|
||||
AckWait: 30 * time.Minute,
|
||||
MaxDelivery: 3,
|
||||
DedupWindow: 2 * time.Hour,
|
||||
RetryBackoffDuration: 5 * time.Second,
|
||||
MaxRetries: 14,
|
||||
},
|
||||
@@ -71,6 +74,9 @@ func EnsureDefaults(cfg *config.Config) {
|
||||
}
|
||||
}
|
||||
|
||||
// Sanitize does nothing atm
|
||||
// Sanitize sanitizes the config
|
||||
func Sanitize(cfg *config.Config) {
|
||||
if cfg.Postprocessing.Workers < 1 {
|
||||
cfg.Postprocessing.Workers = 1
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/eventdedup"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
"github.com/owncloud/ocis/v2/services/postprocessing/pkg/config"
|
||||
"github.com/owncloud/ocis/v2/services/postprocessing/pkg/postprocessing"
|
||||
@@ -56,6 +57,12 @@ func NewPostprocessingService(ctx context.Context, stream events.Stream, logger
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if c.DedupWindow > 0 {
|
||||
evs = eventdedup.Filter(evs, eventdedup.NewSeen(c.DedupWindow), func(e events.Event) {
|
||||
logger.Info().Str("eventID", e.ID).Str("type", e.Type).Msg("dropping redelivered duplicate event")
|
||||
})
|
||||
}
|
||||
|
||||
return &PostprocessingService{
|
||||
ctx: ctx,
|
||||
log: logger,
|
||||
|
||||
@@ -137,6 +137,24 @@ func DefaultPolicies() []config.Policy {
|
||||
Endpoint: "/branding/logo",
|
||||
Service: "com.owncloud.web.web",
|
||||
},
|
||||
{
|
||||
// Reverse Cloud: Discord login admin API, requires an authenticated user.
|
||||
// Must come before the unprotected /oauth2/discord/ route (first prefix match wins).
|
||||
Endpoint: "/oauth2/discord/admin/",
|
||||
Service: "com.owncloud.web.idp",
|
||||
},
|
||||
{
|
||||
// Reverse Cloud: Discord account linking API, requires an authenticated user.
|
||||
// Must come before the unprotected /oauth2/discord/ route (first prefix match wins).
|
||||
Endpoint: "/oauth2/discord/account/",
|
||||
Service: "com.owncloud.web.idp",
|
||||
},
|
||||
{
|
||||
// Reverse Cloud: Discord OAuth2 login and callback.
|
||||
Endpoint: "/oauth2/discord/",
|
||||
Service: "com.owncloud.web.idp",
|
||||
Unprotected: true,
|
||||
},
|
||||
{
|
||||
Endpoint: "/konnect/",
|
||||
Service: "com.owncloud.web.idp",
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
[main]
|
||||
host = https://www.transifex.com
|
||||
|
||||
[o:owncloud-org:p:owncloud-web:r:ocis-settings]
|
||||
file_filter = locale/<lang>/LC_MESSAGES/settings.po
|
||||
minimum_perc = 75
|
||||
resource_name = ocis-settings
|
||||
source_file = settings.pot
|
||||
source_lang = en
|
||||
type = PO
|
||||
@@ -4,8 +4,10 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os/signal"
|
||||
"time"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/config/configlog"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/natsconsumer"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/registry"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/runner"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/tracing"
|
||||
@@ -17,6 +19,7 @@ import (
|
||||
"github.com/owncloud/ocis/v2/services/storage-users/pkg/revaconfig"
|
||||
"github.com/owncloud/ocis/v2/services/storage-users/pkg/server/debug"
|
||||
"github.com/owncloud/reva/v2/cmd/revad/runtime"
|
||||
revaevents "github.com/owncloud/reva/v2/pkg/events"
|
||||
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
@@ -95,6 +98,30 @@ func Server(cfg *config.Config) *cli.Command {
|
||||
return err
|
||||
}
|
||||
|
||||
// The decomposedfs consumer is created by reva once the storage
|
||||
// provider starts; Ensure retries until it exists.
|
||||
go func() {
|
||||
group := cfg.Events.ConsumerGroup
|
||||
if group == "" {
|
||||
group = "dcfs"
|
||||
}
|
||||
err := natsconsumer.Ensure(ctx, logger, natsconsumer.Connection{
|
||||
Endpoint: cfg.Events.Addr,
|
||||
Name: cfg.Service.Name + "-consumer-config",
|
||||
EnableTLS: cfg.Events.EnableTLS,
|
||||
TLSInsecure: cfg.Events.TLSInsecure,
|
||||
TLSRootCACertificate: cfg.Events.TLSRootCaCertPath,
|
||||
AuthUsername: cfg.Events.AuthUsername,
|
||||
AuthPassword: cfg.Events.AuthPassword,
|
||||
}, revaevents.MainQueueName, group, natsconsumer.Settings{
|
||||
AckWait: cfg.Events.AckWait,
|
||||
MaxDeliver: cfg.Events.MaxDelivery,
|
||||
}, 5*time.Second)
|
||||
if err != nil {
|
||||
logger.Error().Err(err).Str("consumer", group).Msg("could not apply NATS consumer settings")
|
||||
}
|
||||
}()
|
||||
|
||||
eventSVC, err := event.NewService(ctx, selector, stream, traceProvider, logger, *cfg)
|
||||
if err != nil {
|
||||
logger.Fatal().Err(err).Msg("can't create event handler")
|
||||
|
||||
@@ -211,43 +211,45 @@ type PosixDriver struct {
|
||||
|
||||
// Events combines the configuration options for the event bus.
|
||||
type Events struct {
|
||||
Addr string `yaml:"endpoint" env:"OCIS_EVENTS_ENDPOINT;STORAGE_USERS_EVENTS_ENDPOINT" desc:"The address of the event system. The event system is the message queuing service. It is used as message broker for the microservice architecture." introductionVersion:"pre5.0"`
|
||||
ClusterID string `yaml:"cluster" env:"OCIS_EVENTS_CLUSTER;STORAGE_USERS_EVENTS_CLUSTER" desc:"The clusterID of the event system. The event system is the message queuing service. It is used as message broker for the microservice architecture. Mandatory when using NATS as event system." introductionVersion:"pre5.0"`
|
||||
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_INSECURE;STORAGE_USERS_EVENTS_TLS_INSECURE" desc:"Whether to verify the server TLS certificates." introductionVersion:"pre5.0"`
|
||||
TLSRootCaCertPath string `yaml:"tls_root_ca_cert_path" env:"OCIS_EVENTS_TLS_ROOT_CA_CERTIFICATE;STORAGE_USERS_EVENTS_TLS_ROOT_CA_CERTIFICATE" desc:"The root CA certificate used to validate the server's TLS certificate. If provided STORAGE_USERS_EVENTS_TLS_INSECURE will be seen as false." introductionVersion:"pre5.0"`
|
||||
EnableTLS bool `yaml:"enable_tls" env:"OCIS_EVENTS_ENABLE_TLS;STORAGE_USERS_EVENTS_ENABLE_TLS" desc:"Enable TLS for the connection to the events broker. The events broker is the ocis service which receives and delivers events between the services." introductionVersion:"pre5.0"`
|
||||
NumConsumers int `yaml:"num_consumers" env:"STORAGE_USERS_EVENTS_NUM_CONSUMERS" desc:"The amount of concurrent event consumers to start. Event consumers are used for post-processing files. Multiple consumers increase parallelisation, but will also increase CPU and memory demands. The setting has no effect when the OCIS_ASYNC_UPLOADS is set to false. The default and minimum value is 1." introductionVersion:"pre5.0"`
|
||||
ConsumerGroup string `yaml:"consumer_group" env:"STORAGE_USERS_EVENTS_CONSUMER_GROUP" desc:"The name of the consumer group to be used at the event to help consumers identify the unique group." introductionVersion:"8.1.0"`
|
||||
AuthUsername string `yaml:"username" env:"OCIS_EVENTS_AUTH_USERNAME;STORAGE_USERS_EVENTS_AUTH_USERNAME" desc:"The username to authenticate with the events broker. The events broker is the ocis service which receives and delivers events between the services." introductionVersion:"5.0"`
|
||||
AuthPassword string `yaml:"password" env:"OCIS_EVENTS_AUTH_PASSWORD;STORAGE_USERS_EVENTS_AUTH_PASSWORD" desc:"The password to authenticate with the events broker. The events broker is the ocis service which receives and delivers events between the services." introductionVersion:"5.0"`
|
||||
Addr string `yaml:"endpoint" env:"OCIS_EVENTS_ENDPOINT;STORAGE_USERS_EVENTS_ENDPOINT" desc:"The address of the event system. The event system is the message queuing service. It is used as message broker for the microservice architecture." introductionVersion:"pre5.0"`
|
||||
ClusterID string `yaml:"cluster" env:"OCIS_EVENTS_CLUSTER;STORAGE_USERS_EVENTS_CLUSTER" desc:"The clusterID of the event system. The event system is the message queuing service. It is used as message broker for the microservice architecture. Mandatory when using NATS as event system." introductionVersion:"pre5.0"`
|
||||
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_INSECURE;STORAGE_USERS_EVENTS_TLS_INSECURE" desc:"Whether to verify the server TLS certificates." introductionVersion:"pre5.0"`
|
||||
TLSRootCaCertPath string `yaml:"tls_root_ca_cert_path" env:"OCIS_EVENTS_TLS_ROOT_CA_CERTIFICATE;STORAGE_USERS_EVENTS_TLS_ROOT_CA_CERTIFICATE" desc:"The root CA certificate used to validate the server's TLS certificate. If provided STORAGE_USERS_EVENTS_TLS_INSECURE will be seen as false." introductionVersion:"pre5.0"`
|
||||
EnableTLS bool `yaml:"enable_tls" env:"OCIS_EVENTS_ENABLE_TLS;STORAGE_USERS_EVENTS_ENABLE_TLS" desc:"Enable TLS for the connection to the events broker. The events broker is the ocis service which receives and delivers events between the services." introductionVersion:"pre5.0"`
|
||||
NumConsumers int `yaml:"num_consumers" env:"STORAGE_USERS_EVENTS_NUM_CONSUMERS" desc:"The amount of concurrent event consumers to start. Event consumers are used for post-processing files. Multiple consumers increase parallelisation, but will also increase CPU and memory demands. The setting has no effect when the OCIS_ASYNC_UPLOADS is set to false. The default and minimum value is 1." introductionVersion:"pre5.0"`
|
||||
ConsumerGroup string `yaml:"consumer_group" env:"STORAGE_USERS_EVENTS_CONSUMER_GROUP" desc:"The name of the consumer group to be used at the event to help consumers identify the unique group." introductionVersion:"8.1.0"`
|
||||
AckWait time.Duration `yaml:"ack_wait" env:"STORAGE_USERS_EVENTS_ACK_WAIT" desc:"How long the NATS JetStream server waits for an acknowledgement before it redelivers an event to the storage postprocessing consumer (the one finalizing uploads into the blobstore). Written to the durable consumer on the server at startup. Set to 0 to keep the current server value. See the Environment Variable Types description for more details." introductionVersion:"8.3.0"`
|
||||
MaxDelivery int `yaml:"max_delivery" env:"STORAGE_USERS_EVENTS_MAX_DELIVERY" desc:"Maximum number of delivery attempts of an event to the storage postprocessing consumer. -1 means unlimited, 0 keeps the current server value." introductionVersion:"8.3.0"`
|
||||
AuthUsername string `yaml:"username" env:"OCIS_EVENTS_AUTH_USERNAME;STORAGE_USERS_EVENTS_AUTH_USERNAME" desc:"The username to authenticate with the events broker. The events broker is the ocis service which receives and delivers events between the services." introductionVersion:"5.0"`
|
||||
AuthPassword string `yaml:"password" env:"OCIS_EVENTS_AUTH_PASSWORD;STORAGE_USERS_EVENTS_AUTH_PASSWORD" desc:"The password to authenticate with the events broker. The events broker is the ocis service which receives and delivers events between the services." introductionVersion:"5.0"`
|
||||
}
|
||||
|
||||
// FilemetadataCache holds cache config
|
||||
type FilemetadataCache struct {
|
||||
Store string `yaml:"store" env:"OCIS_CACHE_STORE;STORAGE_USERS_FILEMETADATA_CACHE_STORE" desc:"The type of the cache store. Supported values are: 'memory', 'redis-sentinel', 'nats-js-kv', 'noop'. See the text description for details." introductionVersion:"pre5.0"`
|
||||
Nodes []string `yaml:"nodes" env:"OCIS_CACHE_STORE_NODES;STORAGE_USERS_FILEMETADATA_CACHE_STORE_NODES" desc:"A list of nodes to access the configured store. This has no effect when 'memory' store is configured. Note that the behaviour how nodes are used is dependent on the library of the configured store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
Database string `yaml:"database" env:"OCIS_CACHE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"pre5.0"`
|
||||
TTL time.Duration `yaml:"ttl" env:"OCIS_CACHE_TTL;STORAGE_USERS_FILEMETADATA_CACHE_TTL" desc:"Default time to live for user info in the user info cache. Only applied when access tokens has no expiration. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
DisablePersistence bool `yaml:"disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;STORAGE_USERS_FILEMETADATA_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"5.0"`
|
||||
AuthUsername string `yaml:"username" env:"OCIS_CACHE_AUTH_USERNAME;STORAGE_USERS_FILEMETADATA_CACHE_AUTH_USERNAME" desc:"The username to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
AuthPassword string `yaml:"password" env:"OCIS_CACHE_AUTH_PASSWORD;STORAGE_USERS_FILEMETADATA_CACHE_AUTH_PASSWORD" desc:"The password to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;STORAGE_USERS_FILEMETADATA_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;STORAGE_USERS_FILEMETADATA_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;STORAGE_USERS_FILEMETADATA_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
Store string `yaml:"store" env:"OCIS_CACHE_STORE;STORAGE_USERS_FILEMETADATA_CACHE_STORE" desc:"The type of the cache store. Supported values are: 'memory', 'redis-sentinel', 'nats-js-kv', 'noop'. See the text description for details." introductionVersion:"pre5.0"`
|
||||
Nodes []string `yaml:"nodes" env:"OCIS_CACHE_STORE_NODES;STORAGE_USERS_FILEMETADATA_CACHE_STORE_NODES" desc:"A list of nodes to access the configured store. This has no effect when 'memory' store is configured. Note that the behaviour how nodes are used is dependent on the library of the configured store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
Database string `yaml:"database" env:"OCIS_CACHE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"pre5.0"`
|
||||
TTL time.Duration `yaml:"ttl" env:"OCIS_CACHE_TTL;STORAGE_USERS_FILEMETADATA_CACHE_TTL" desc:"Default time to live for user info in the user info cache. Only applied when access tokens has no expiration. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
DisablePersistence bool `yaml:"disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;STORAGE_USERS_FILEMETADATA_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"5.0"`
|
||||
AuthUsername string `yaml:"username" env:"OCIS_CACHE_AUTH_USERNAME;STORAGE_USERS_FILEMETADATA_CACHE_AUTH_USERNAME" desc:"The username to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
AuthPassword string `yaml:"password" env:"OCIS_CACHE_AUTH_PASSWORD;STORAGE_USERS_FILEMETADATA_CACHE_AUTH_PASSWORD" desc:"The password to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;STORAGE_USERS_FILEMETADATA_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;STORAGE_USERS_FILEMETADATA_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;STORAGE_USERS_FILEMETADATA_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
}
|
||||
|
||||
// IDCache holds cache config
|
||||
type IDCache struct {
|
||||
Store string `yaml:"store" env:"OCIS_CACHE_STORE;STORAGE_USERS_ID_CACHE_STORE" desc:"The type of the cache store. Supported values are: 'memory', 'redis-sentinel', 'nats-js-kv', 'noop'. See the text description for details." introductionVersion:"pre5.0"`
|
||||
Nodes []string `yaml:"nodes" env:"OCIS_CACHE_STORE_NODES;STORAGE_USERS_ID_CACHE_STORE_NODES" desc:"A list of nodes to access the configured store. This has no effect when 'memory' store is configured. Note that the behaviour how nodes are used is dependent on the library of the configured store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
Database string `yaml:"database" env:"OCIS_CACHE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"pre5.0"`
|
||||
TTL time.Duration `yaml:"ttl" env:"OCIS_CACHE_TTL;STORAGE_USERS_ID_CACHE_TTL" desc:"Default time to live for user info in the user info cache. Only applied when access tokens have no expiration. Defaults to 300s which is derived from the underlaying package though not explicitly set as default. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
DisablePersistence bool `yaml:"disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;STORAGE_USERS_ID_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"5.0"`
|
||||
AuthUsername string `yaml:"username" env:"OCIS_CACHE_AUTH_USERNAME;STORAGE_USERS_ID_CACHE_AUTH_USERNAME" desc:"The username to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
AuthPassword string `yaml:"password" env:"OCIS_CACHE_AUTH_PASSWORD;STORAGE_USERS_ID_CACHE_AUTH_PASSWORD" desc:"The password to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;STORAGE_USERS_ID_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;STORAGE_USERS_ID_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;STORAGE_USERS_ID_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
Store string `yaml:"store" env:"OCIS_CACHE_STORE;STORAGE_USERS_ID_CACHE_STORE" desc:"The type of the cache store. Supported values are: 'memory', 'redis-sentinel', 'nats-js-kv', 'noop'. See the text description for details." introductionVersion:"pre5.0"`
|
||||
Nodes []string `yaml:"nodes" env:"OCIS_CACHE_STORE_NODES;STORAGE_USERS_ID_CACHE_STORE_NODES" desc:"A list of nodes to access the configured store. This has no effect when 'memory' store is configured. Note that the behaviour how nodes are used is dependent on the library of the configured store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
Database string `yaml:"database" env:"OCIS_CACHE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"pre5.0"`
|
||||
TTL time.Duration `yaml:"ttl" env:"OCIS_CACHE_TTL;STORAGE_USERS_ID_CACHE_TTL" desc:"Default time to live for user info in the user info cache. Only applied when access tokens have no expiration. Defaults to 300s which is derived from the underlaying package though not explicitly set as default. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
DisablePersistence bool `yaml:"disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;STORAGE_USERS_ID_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"5.0"`
|
||||
AuthUsername string `yaml:"username" env:"OCIS_CACHE_AUTH_USERNAME;STORAGE_USERS_ID_CACHE_AUTH_USERNAME" desc:"The username to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
AuthPassword string `yaml:"password" env:"OCIS_CACHE_AUTH_PASSWORD;STORAGE_USERS_ID_CACHE_AUTH_PASSWORD" desc:"The password to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;STORAGE_USERS_ID_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;STORAGE_USERS_ID_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;STORAGE_USERS_ID_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
}
|
||||
|
||||
// S3Driver is the storage driver configuration when using 's3' storage driver
|
||||
|
||||
@@ -151,9 +151,12 @@ func DefaultConfig() *config.Config {
|
||||
},
|
||||
},
|
||||
Events: config.Events{
|
||||
Addr: "127.0.0.1:9233",
|
||||
ClusterID: "ocis-cluster",
|
||||
EnableTLS: false,
|
||||
Addr: "127.0.0.1:9233",
|
||||
ClusterID: "ocis-cluster",
|
||||
EnableTLS: false,
|
||||
NumConsumers: 4,
|
||||
AckWait: 30 * time.Minute,
|
||||
MaxDelivery: 3,
|
||||
},
|
||||
FilemetadataCache: config.FilemetadataCache{
|
||||
Store: "memory",
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
[main]
|
||||
host = https://www.transifex.com
|
||||
|
||||
[o:owncloud-org:p:owncloud-web:r:ocis-userlog]
|
||||
file_filter = locale/<lang>/LC_MESSAGES/userlog.po
|
||||
minimum_perc = 75
|
||||
resource_name = ocis-userlog
|
||||
source_file = userlog.pot
|
||||
source_lang = en
|
||||
type = PO
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"common": {
|
||||
"name": "ownCloud",
|
||||
"slogan": "ownCloud – A safe home for all your data",
|
||||
"name": "Reverse Cloud",
|
||||
"slogan": "Reverse Cloud – プライベートクラウドストレージ",
|
||||
"logo": "themes/owncloud/assets/logo.svg",
|
||||
"urls": {
|
||||
"accessDeniedHelp": "",
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
|
||||
sonar.projectKey=owncloud_ocis
|
||||
sonar.organization=owncloud-1
|
||||
sonar.projectName=ocis
|
||||
sonar.projectVersion=8.2.2
|
||||
sonar.host.url=https://sonarcloud.io
|
||||
|
||||
# =====================================================
|
||||
# Meta-data for the project
|
||||
# =====================================================
|
||||
|
||||
sonar.links.homepage=https://github.com/owncloud/ocis
|
||||
sonar.links.ci=https://drone.owncloud.com/owncloud/ocis/
|
||||
sonar.links.scm=https://github.com/owncloud/ocis
|
||||
sonar.links.issue=https://github.com/owncloud/ocis/issues
|
||||
|
||||
# =====================================================
|
||||
# Properties that will be shared amongst all modules
|
||||
# =====================================================
|
||||
|
||||
# SQ standard properties
|
||||
sonar.sources=.
|
||||
|
||||
# Pull Requests
|
||||
sonar.pullrequest.provider=github
|
||||
sonar.pullrequest.github.repository=owncloud/ocis
|
||||
sonar.pullrequest.base=${env.SONAR_PULL_REQUEST_BASE}
|
||||
sonar.pullrequest.branch=${env.SONAR_PULL_REQUEST_BRANCH}
|
||||
sonar.pullrequest.key=${env.SONAR_PULL_REQUEST_KEY}
|
||||
|
||||
# Properties specific to language plugins:
|
||||
sonar.go.coverage.reportPaths=cache/coverage/*
|
||||
sonar.go.golangci-lint.reportPaths=cache/checkstyle/checkstyle.xml
|
||||
|
||||
# Exclude files
|
||||
sonar.exclusions=**/third_party,docs/**,changelog/**,**/package.json,**/rollup.config.js,CHANGELOG.md,deployments/**,tests/**,vendor/**,vendor-bin/**,README.md,**/mocks/**,/protogen/**,**/*_gen.go
|
||||
sonar.coverage.exclusions=**/*_test.go,**mocks/**,/protogen/**,**/*_gen.go
|
||||
sonar.cpd.exclusions=**/defaultconfig.go,**/*_test.go,**/revaconfig/**,services/settings/pkg/store/defaults/defaults.go
|
||||
|
||||
# Rule exclusions
|
||||
sonar.issue.ignore.multicriteria=g1,g2
|
||||
|
||||
# Ignore "Define a constant instead of duplicating this literal" rule for tests
|
||||
sonar.issue.ignore.multicriteria.g1.ruleKey=go:S1192
|
||||
sonar.issue.ignore.multicriteria.g1.resourceKey=**/*_test.go
|
||||
|
||||
# Ignore "Rename function XXX to match the regular expression ^(_|[a-zA-Z0-9]+)$" rule for tests
|
||||
sonar.issue.ignore.multicriteria.g2.ruleKey=go:S100
|
||||
sonar.issue.ignore.multicriteria.g2.resourceKey=**/*_test.go
|
||||
|
||||
# Timeout for web requests
|
||||
#sonar.ws.timeout=60 is the default, but we need to increase it to deal with timeouts when loading defaults
|
||||
sonar.ws.timeout=120
|
||||
@@ -1,10 +0,0 @@
|
||||
[main]
|
||||
host = https://www.transifex.com
|
||||
|
||||
[o:owncloud-org:p:owncloud-web:r:design-system]
|
||||
file_filter = locale/<lang>/app.po
|
||||
minimum_perc = 0
|
||||
resource_name = web-design-system
|
||||
source_file = template.pot
|
||||
source_lang = en
|
||||
type = PO
|
||||
@@ -1 +1 @@
|
||||
{"af":{},"ar":{"Cancel":"إلغاء","Close":"غلق","Copy":"نسخ","Details":"التفاصيل","Search":"بحث"},"bs":{},"bg":{"Cancel":"Отказ","Clear filter":"Изчистване на филтъра","Clear input":"Изчистване на въведеното","Close":"Затваряне","Copied":"Копирано","Copy":"Копиране","Deselect %{label}":"Премахване на избора от %{label}","Details":"Подробности","Go to page %{ page }":"Към страница %{ page }","Go to the next page":"Към следващата страница","Go to the previous page":"Към предишната страница","Loading avatar":"Зареждане на аватар","Loading results":"Зареждане на резултати","Navigate one level up":"Преминаване с едно ниво нагоре","No options available.":"Няма налични опции.","Pagination":"Странициране","Read more":"Прочетете още","Search":"Търсене","Show actions for current folder":"Показване на действията за текущата папка"},"ca":{"Activity":"Activitat","Add custom emoji":"Afegeix un emoji personalitzat","Animals & Nature":"Animals i natura","Breadcrumbs":"Ruta navegada","Cancel":"Cancel·la","Choose default skin tone":"Tria el mode de l'aparença per defecte","Clear date":"Neteja la data","Clear filter":"Neteja el filtre","Clear input":"Neteja l'entrada","Close":"Tanca","Copied":"Copiat","Copy":"Copia","Copy password":"Copia la contrasenya","Copy the following information and pass them to technical support to troubleshoot the problem:":"Copiar la següent informació i passa-la al suport tècnic per resoldre el problema:","Custom":"Personalitzat","Dark":"Fosc","Default":"Per defecte","Deselect %{label}":"Desselecciona %{label}","Details":"Detalls","Flags":"Banderes","Food & Drink":"Menjar i beguda","Frequently used":"Utilitzats freqüentment","Fulfilled":"Complert","Generate password":"Genera contrasenya","Go to page %{ page }":"Ves a la pàgina %{ page }","Go to the next page":"Ves a la pàgina següent","Go to the previous page":"Ves a la pàgina anterior","Hide password":"Amaga contrasenya","Light":"Clar","Loading avatar":"Carregant l'avatar","Loading results":"Carregant resultats","Medium":"Mitjà","Medium-Dark":"Mitjà-Fosc","Medium-Light":"Mitjà-Clar","Navigate one level up":"Navega a un nivell superior","No options available.":"No hi ha opcions disponibles.","Not fulfilled":"No complert","Objects":"Objectes","Oh no!":"Oh, no!","Pagination":"Paginació","Password meets all requirements":"La contrasenya compleix tots els requisits","Password policy":"Política de contrasenyes","Password requirements: %{requirements}":"Requisits de contrasenya: %{requirements}","Pick an emoji…":"Trieu un emoji...","Read more":"Llegeix més","Search":"Cerca","Search Results":"Resultats de la cerca","Show actions for current folder":"Mostra les accions per a la carpeta actual","Show more information":"Mostra més informació","Show password":"Mostra la contrasenya","Smileys & People":"Somriures i persones","Symbols":"Símbols","That emoji couldn’t be found":"No s'ha pogut trobar l'emoji","The date must be after %{date}":"La data ha de ser posterior a %{date}","Travel & Places":"Viatges i llocs","Icons":{"Sets a hidden table header text for screen readers":"Icones"},"Column headers with buttons are sortable.":{"Table component caption sorting explanation available only to screen readers.":"Les capçaleres de columna amb botons són ordenables."}},"cs":{"Cancel":"Zrušit","Clear filter":"Zrušit filter","Clear input":"Vymazat vstup","Close":"Zavřít","Copied":"Zkopírováno","Copy":"Kopírovat","Deselect %{label}":"Zrušit výběr %{label}","Details":"Detaily","Go to page %{ page }":"Jít na stránku %{ page }","Go to the next page":"Jít na další stránku","Go to the previous page":"Jít na předchozí stránku","Loading avatar":"Načítání avatara","Loading results":"Načítání výsledků","Navigate one level up":"Přejít o úroveň výše","No options available.":"Žádné možnosti nejsou dostupné.","Pagination":"Stránkování","Read more":"Číst dále","Search":"Hledat","Show actions for current folder":"Zobrazit akce pro aktuální složku"},"de":{"Activity":"Aktivität","Add custom emoji":"Füge ein benutzerdefiniertes Emoji hinzu","Animals & Nature":"Tiere & Natur","Breadcrumbs":"Brotkrumennavigation","Cancel":"Abbrechen","Choose default skin tone":"Wähle eine Standard-Hautfarbe","Clear date":"Lösche das Datum","Clear filter":"Filter löschen","Clear input":"Eingabe zurücksetzen","Close":"Schließen","Copied":"Kopiert","Copy":"Kopieren","Copy password":"Passwort kopieren","Copy the following information and pass them to technical support to troubleshoot the problem:":"Bitte folgende Information kopieren und an den technischen Support weiterleiten, damit das Problem gelöst werden kannLine truncated
|
||||
{"af":{},"ar":{"Cancel":"إلغاء","Close":"غلق","Copy":"نسخ","Details":"التفاصيل","Search":"بحث"},"bs":{},"bg":{"Cancel":"Отказ","Clear filter":"Изчистване на филтъра","Clear input":"Изчистване на въведеното","Close":"Затваряне","Copied":"Копирано","Copy":"Копиране","Deselect %{label}":"Премахване на избора от %{label}","Details":"Подробности","Go to page %{ page }":"Към страница %{ page }","Go to the next page":"Към следващата страница","Go to the previous page":"Към предишната страница","Loading avatar":"Зареждане на аватар","Loading results":"Зареждане на резултати","Navigate one level up":"Преминаване с едно ниво нагоре","No options available.":"Няма налични опции.","Pagination":"Странициране","Read more":"Прочетете още","Search":"Търсене","Show actions for current folder":"Показване на действията за текущата папка"},"ca":{"Activity":"Activitat","Add custom emoji":"Afegeix un emoji personalitzat","Animals & Nature":"Animals i natura","Breadcrumbs":"Ruta navegada","Cancel":"Cancel·la","Choose default skin tone":"Tria el mode de l'aparença per defecte","Clear date":"Neteja la data","Clear filter":"Neteja el filtre","Clear input":"Neteja l'entrada","Close":"Tanca","Copied":"Copiat","Copy":"Copia","Copy password":"Copia la contrasenya","Copy the following information and pass them to technical support to troubleshoot the problem:":"Copiar la següent informació i passa-la al suport tècnic per resoldre el problema:","Custom":"Personalitzat","Dark":"Fosc","Default":"Per defecte","Deselect %{label}":"Desselecciona %{label}","Details":"Detalls","Flags":"Banderes","Food & Drink":"Menjar i beguda","Frequently used":"Utilitzats freqüentment","Fulfilled":"Complert","Generate password":"Genera contrasenya","Go to page %{ page }":"Ves a la pàgina %{ page }","Go to the next page":"Ves a la pàgina següent","Go to the previous page":"Ves a la pàgina anterior","Hide password":"Amaga contrasenya","Light":"Clar","Loading avatar":"Carregant l'avatar","Loading results":"Carregant resultats","Medium":"Mitjà","Medium-Dark":"Mitjà-Fosc","Medium-Light":"Mitjà-Clar","Navigate one level up":"Navega a un nivell superior","No options available.":"No hi ha opcions disponibles.","Not fulfilled":"No complert","Objects":"Objectes","Oh no!":"Oh, no!","Pagination":"Paginació","Password meets all requirements":"La contrasenya compleix tots els requisits","Password policy":"Política de contrasenyes","Password requirements: %{requirements}":"Requisits de contrasenya: %{requirements}","Pick an emoji…":"Trieu un emoji...","Read more":"Llegeix més","Search":"Cerca","Search Results":"Resultats de la cerca","Show actions for current folder":"Mostra les accions per a la carpeta actual","Show more information":"Mostra més informació","Show password":"Mostra la contrasenya","Smileys & People":"Somriures i persones","Symbols":"Símbols","That emoji couldn’t be found":"No s'ha pogut trobar l'emoji","The date must be after %{date}":"La data ha de ser posterior a %{date}","Travel & Places":"Viatges i llocs","Icons":{"Sets a hidden table header text for screen readers":"Icones"},"Column headers with buttons are sortable.":{"Table component caption sorting explanation available only to screen readers.":"Les capçaleres de columna amb botons són ordenables."}},"cs":{"Cancel":"Zrušit","Clear filter":"Zrušit filter","Clear input":"Vymazat vstup","Close":"Zavřít","Copied":"Zkopírováno","Copy":"Kopírovat","Deselect %{label}":"Zrušit výběr %{label}","Details":"Detaily","Go to page %{ page }":"Jít na stránku %{ page }","Go to the next page":"Jít na další stránku","Go to the previous page":"Jít na předchozí stránku","Loading avatar":"Načítání avatara","Loading results":"Načítání výsledků","Navigate one level up":"Přejít o úroveň výše","No options available.":"Žádné možnosti nejsou dostupné.","Pagination":"Stránkování","Read more":"Číst dále","Search":"Hledat","Show actions for current folder":"Zobrazit akce pro aktuální složku"},"de":{"Activity":"Aktivität","Add custom emoji":"Füge ein benutzerdefiniertes Emoji hinzu","Animals & Nature":"Tiere & Natur","Breadcrumbs":"Brotkrumennavigation","Cancel":"Abbrechen","Choose default skin tone":"Wähle eine Standard-Hautfarbe","Clear date":"Lösche das Datum","Clear filter":"Filter löschen","Clear input":"Eingabe zurücksetzen","Close":"Schließen","Copied":"Kopiert","Copy":"Kopieren","Copy password":"Passwort kopieren","Copy the following information and pass them to technical support to troubleshoot the problem:":"Bitte folgende Information kopieren und an den technischen Support weiterleiten, damit das Problem gelöst werden kannLine truncated
|
||||
@@ -1,10 +0,0 @@
|
||||
[main]
|
||||
host = https://www.transifex.com
|
||||
|
||||
[o:owncloud-org:p:owncloud-web:r:activities]
|
||||
file_filter = locale/<lang>/app.po
|
||||
minimum_perc = 0
|
||||
resource_name = web-activities
|
||||
source_file = template.pot
|
||||
source_lang = en
|
||||
type = PO
|
||||
@@ -1 +1 @@
|
||||
{"af":{},"ar":{},"bg":{"Activities":"Дейности"},"bs":{},"ca":{"Activities":"Activitats","Activity unknown":"Activitat desconeguda","Filter location":"Filtrar ubicació","Location":"Ubicació","No activities found":"No s'ha trobat cap activitat","The resource is unavailable, it may have been deleted.":"El recurs no està disponible, pot ser que s'hagi suprimit."},"cs":{"Activities":"Aktivity"},"de":{"Activities":"Aktivitäten","Activity unknown":"Unbekannte Aktivität","Filter location":"Ort filtern","Location":"Ort","No activities found":"Keine Aktivitäten gefunden","The resource is unavailable, it may have been deleted.":"Die Ressource ist nicht mehr verfügbar, sie wurde möglicherweise gelöscht."},"el":{},"es":{"Activities":"Actividades","Activity unknown":"Actividad desconocida","Filter location":"Filtrar ubicación","Location":"Localización","No activities found":"Sin actividades","The resource is unavailable, it may have been deleted.":"El recurso no está disponible, puede haber sido borrado."},"et":{},"fr":{"Activities":"Activités","Activity unknown":"Activité inconnue","Filter location":"Filter la localisation","Location":"Localisation","No activities found":"Aucune activité trouvée","The resource is unavailable, it may have been deleted.":"La ressource n'est pas disponible, elle a peut-être été supprimée."},"gl":{},"he":{"Activities":"פעילויות","Activity unknown":"פעילות לא ידועה","Filter location":"סינון מיקום","Location":"מיקום","No activities found":"לא נמצאו פעילויות","The resource is unavailable, it may have been deleted.":"המשאב לא זמין, ייתכן והוא נמחק."},"hr":{"Activities":"Aktivnosti","Filter location":"Filtriraj lokaciju","Location":"Lokacija","No activities found":"Nema pronađenih aktivnosti","The resource is unavailable, it may have been deleted.":"Ovaj resurs je nedostupan, moguče da je izbrisan."},"id":{"Activities":"Aktifitas","Filter location":"Lokasi filter","Location":"Lokasi","No activities found":"Aktifitas tidak ditemukan","The resource is unavailable, it may have been deleted.":"Sumber daya tidak tersedia, mungkin telah dihapus."},"it":{"Activities":"Attività","Activity unknown":"Attività sconosciuta","Filter location":"Filtro posizione","Location":"Posizione","No activities found":"Nessuna attività trovata","The resource is unavailable, it may have been deleted.":"La risorsa non è disponibile, potrebbe essere stata cancellata."},"ja":{"Activities":"アクティビティー"},"nl":{"Activities":"Activiteit","Filter location":"Locatie filteren","Location":"Locatie","No activities found":"Geen activiteiten gevonden","The resource is unavailable, it may have been deleted.":"De bron is niet beschikbaar, deze is mogelijk verwijderd."},"pl":{"Activities":"Aktywności","Location":"Lokalizacja"},"pt":{"Activities":"Atividades","Activity unknown":"Atividade desconhecida","Filter location":"Filtrar localização","Location":"Localização","No activities found":"Nenhuma atividade encontrada","The resource is unavailable, it may have been deleted.":"O recurso está indisponível, ele pode ter sido excluído."},"ka":{},"ko":{"Activities":"활동"},"ro":{},"ru":{"Activities":"Активности","Activity unknown":"Неизвестная деятельность","Filter location":"Фильтр местоположения","Location":"Местоположение","No activities found":"Нет найденных активностей","The resource is unavailable, it may have been deleted.":"Ресурс недоступен, возможно, он был удален."},"si":{},"sk":{},"sq":{"Activities":"Veprimtari","Activity unknown":"Veprimtari e panjohur","Filter location":"Filtro vendndodhjen","Location":"Vendndodhje","No activities found":"S’u gjetën veprimtari","The resource is unavailable, it may have been deleted.":"Burimi s’gjendet, mund të jetë fshirë."},"sr":{},"sv":{"Activities":"Aktiviteter"},"ta":{},"tr":{"Activities":"Aktiviteler"},"ug":{},"uk":{"Activities":"Активності","Activity unknown":"Активність невідома","Filter location":"Фільтр розташування","Location":"Місцезнаходження","No activities found":"Активностей не знайдено","The resource is unavailable, it may have been deleted.":"Ресурс недоступний, можливо його видалили."},"zh":{"Activities":"活动"}}
|
||||
{"af":{},"ar":{},"bg":{"Activities":"Дейности"},"bs":{},"ca":{"Activities":"Activitats","Activity unknown":"Activitat desconeguda","Filter location":"Filtrar ubicació","Location":"Ubicació","No activities found":"No s'ha trobat cap activitat","The resource is unavailable, it may have been deleted.":"El recurs no està disponible, pot ser que s'hagi suprimit."},"cs":{"Activities":"Aktivity"},"de":{"Activities":"Aktivitäten","Activity unknown":"Unbekannte Aktivität","Filter location":"Ort filtern","Location":"Ort","No activities found":"Keine Aktivitäten gefunden","The resource is unavailable, it may have been deleted.":"Die Ressource ist nicht mehr verfügbar, sie wurde möglicherweise gelöscht."},"el":{},"es":{"Activities":"Actividades","Activity unknown":"Actividad desconocida","Filter location":"Filtrar ubicación","Location":"Localización","No activities found":"Sin actividades","The resource is unavailable, it may have been deleted.":"El recurso no está disponible, puede haber sido borrado."},"et":{},"fr":{"Activities":"Activités","Activity unknown":"Activité inconnue","Filter location":"Filter la localisation","Location":"Localisation","No activities found":"Aucune activité trouvée","The resource is unavailable, it may have been deleted.":"La ressource n'est pas disponible, elle a peut-être été supprimée."},"gl":{},"he":{"Activities":"פעילויות","Activity unknown":"פעילות לא ידועה","Filter location":"סינון מיקום","Location":"מיקום","No activities found":"לא נמצאו פעילויות","The resource is unavailable, it may have been deleted.":"המשאב לא זמין, ייתכן והוא נמחק."},"hr":{"Activities":"Aktivnosti","Filter location":"Filtriraj lokaciju","Location":"Lokacija","No activities found":"Nema pronađenih aktivnosti","The resource is unavailable, it may have been deleted.":"Ovaj resurs je nedostupan, moguče da je izbrisan."},"id":{"Activities":"Aktifitas","Filter location":"Lokasi filter","Location":"Lokasi","No activities found":"Aktifitas tidak ditemukan","The resource is unavailable, it may have been deleted.":"Sumber daya tidak tersedia, mungkin telah dihapus."},"it":{"Activities":"Attività","Activity unknown":"Attività sconosciuta","Filter location":"Filtro posizione","Location":"Posizione","No activities found":"Nessuna attività trovata","The resource is unavailable, it may have been deleted.":"La risorsa non è disponibile, potrebbe essere stata cancellata."},"ja":{"Activities":"アクティビティ","Activity unknown":"不明なアクティビティ","Filter location":"場所で絞り込み","Location":"場所","No activities found":"アクティビティはありません","The resource is unavailable, it may have been deleted.":"このアイテムは利用できません。削除された可能性があります。"},"nl":{"Activities":"Activiteit","Filter location":"Locatie filteren","Location":"Locatie","No activities found":"Geen activiteiten gevonden","The resource is unavailable, it may have been deleted.":"De bron is niet beschikbaar, deze is mogelijk verwijderd."},"pl":{"Activities":"Aktywności","Location":"Lokalizacja"},"pt":{"Activities":"Atividades","Activity unknown":"Atividade desconhecida","Filter location":"Filtrar localização","Location":"Localização","No activities found":"Nenhuma atividade encontrada","The resource is unavailable, it may have been deleted.":"O recurso está indisponível, ele pode ter sido excluído."},"ka":{},"ko":{"Activities":"활동"},"ro":{},"ru":{"Activities":"Активности","Activity unknown":"Неизвестная деятельность","Filter location":"Фильтр местоположения","Location":"Местоположение","No activities found":"Нет найденных активностей","The resource is unavailable, it may have been deleted.":"Ресурс недоступен, возможно, он был удален."},"si":{},"sk":{},"sq":{"Activities":"Veprimtari","Activity unknown":"Veprimtari e panjohur","Filter location":"Filtro vendndodhjen","Location":"Vendndodhje","No activities found":"S’u gjetën veprimtari","The resource is unavailable, it may have been deleted.":"Burimi s’gjendet, mund të jetë fshirë."},"sr":{},"sv":{"Activities":"Aktiviteter"},"ta":{},"tr":{"Activities":"Aktiviteler"},"ug":{},"uk":{"Activities":"Активності","Activity unknown":"Активність невідома","Filter location":"Фільтр розташування","Location":"Місцезнаходження","No activities found":"Активностей не знайдено","The resource is unavailable, it may have been deleted.":"Ресурс недоступний, можливо його видалили."},"zh":{"Activities":"活动"}}
|
||||
@@ -1,10 +0,0 @@
|
||||
[main]
|
||||
host = https://www.transifex.com
|
||||
|
||||
[o:owncloud-org:p:owncloud-web:r:admin-settings]
|
||||
file_filter = locale/<lang>/app.po
|
||||
minimum_perc = 0
|
||||
resource_name = web-admin-settings
|
||||
source_file = template.pot
|
||||
source_lang = en
|
||||
type = PO
|
||||
@@ -1 +1 @@
|
||||
{"af":{},"ar":{"%{count} groups selected":"٪{عدد} المجموعات المحددة","%{count} users selected":"٪{عدد} المستخدمين المحددين","Actions":"إجراءات","Add to groups":"إضافة إلى المجموعات","Administration Settings":"إعدادات الإدارة","Allowed":"مسموح","Appearance":"ظهور","Create group":"إنشاء مجموعة","Create user":"إنشاء مستخدم","Delete":"حذف","Details":"التفاصيل","Disabled":"تعطيل","Edit":"يحرر","Edit group":"تحرير المجموعة","Edit login":"تعديل تسجيل الدخول","Edit quota":"تعديل الحصة النسبية","Edit user":"تحرير المستخدم","Edition":"الطبعه","Email":"بريد إلكتروني","Enabled":"تمكين","Failed to create group":"فشل إنشاء مجموعة","Failed to create user":"فشل إنشاء مستخدم","Failed to edit group":"فشل تحرير المجموعة","Failed to edit user":"فشل تحرير المستخدم","Failed to reset logo":"فشل إعادة تعيين الشعار","Failed to upload logo":"فشل تحميل الشعار","Filter groups":"تصفية المجموعات","Filter members":"تصفية الأعضاء","Filter roles":"تصفية الأدوار","Filter:":"تصفيه","First and last name":"الاسم الأول والأخير","First and last name cannot be empty":"لا يمكن أن يكون الاسم الأول واسم العائلة فارغين","First and last name cannot exceed 255 characters":"لا يمكن أن يتجاوز الاسم الأول والأخير 255 حرفا","Forbidden":"ممنوع","General":"عام","Group name":"اسم المجموعة","Group name cannot be empty":"لا يمكن أن يكون اسم المجموعة فارغا","Group name cannot exceed 255 characters":"لا يمكن أن يتجاوز اسم المجموعة 255 حرفا","Group was created successfully":"تم إنشاء المجموعة بنجاح","Groups":"المجموعات","Info":"معلومات","Login":"تسجيل الدخول","Logo":"شعار","Logo was reset successfully. Reloading page...":"تمت إعادة تعيين الشعار بنجاح. إعادة تحميل الصفحة","Logo was uploaded successfully":"تم تحميل الشعار بنجاح","Manager":"مدير","Members":"اعضاء","Modified":"تم التعديل","Name":"اسم","New group":"مجموعة جديدة","New user":"مستخدم جديد","No groups assigned.":"لم يتم تعيين مجموعات","No members found":"لم يتم العثور على أعضاء","No restriction":"لا قيود","No spaces in here":"لا توجد مسافات هنا","No users in here":"لا يوجد مستخدمون هنا","Overview of the information about the selected group":"نظرة عامة على المعلومات حول المجموعة المحددة","Overview of the information about the selected user":"نظرة عامة على المعلومات حول المستخدم المحدد","ownCloud":"السحابة الخاصة","Password":"كلمة المرور","Password cannot be empty":"لا يمكن أن تكون كلمة المرور فارغة","Personal quota":"الحصة الشخصية","Please enter a valid email":"الرجاء إدخال بريد إلكتروني صحيح","Quota":"الحصه النسبيه","Quota will only be applied to users who logged in at least once.":"سيتم تطبيق الحصة النسبية فقط على المستخدمين الذين قاموا بتسجيل الدخول مرة واحدة على الأقل.","Remaining quota":"الحصة المتبقية","Remove from groups":"إزالة من المجموعات","Reset logo":"إعادة تعيين الشعار","Role":"دور","Roles":"ادوار","Search":"بحث","Select a group to view details":"حدد مجموعة لعرض التفاصيل","Select a user to view details":"حدد مستخدما لعرض التفاصيل","Select all groups":"حدد كل المجموعات","Select all spaces":"حدد كل المسافات","Select all users":"حدد جميع المستخدمين","Select...":"اختار...","Show context menu":"إظهار قائمة السياق","Show details":"اظهر التفاصيل","Spaces":"مسافات","Status":"حالة","The file type is unsupported":"نوع الملف غير معتمد","This group is read-only and can't be edited":"هذه المجموعة للقراءة فقط ولا يمكن تحريرها","To set an individual quota, the user needs to have logged in once.":"لتعيين حصة فردية ، يحتاج المستخدم إلى تسجيل الدخول مرة واحدة.","Total quota":"إجمالي الحصة","Unaffected users":"المستخدمون غير المتأثرين","Upload logo":"تحميل الشعار","Used quota":"الحصة المستخدمة","User name":"اسم المستخدم","User name cannot be empty":"لا يمكن أن يكون اسم المLine truncated
|
||||
{"af":{},"ar":{"%{count} groups selected":"٪{عدد} المجموعات المحددة","%{count} users selected":"٪{عدد} المستخدمين المحددين","Actions":"إجراءات","Add to groups":"إضافة إلى المجموعات","Administration Settings":"إعدادات الإدارة","Allowed":"مسموح","Appearance":"ظهور","Create group":"إنشاء مجموعة","Create user":"إنشاء مستخدم","Delete":"حذف","Details":"التفاصيل","Disabled":"تعطيل","Edit":"يحرر","Edit group":"تحرير المجموعة","Edit login":"تعديل تسجيل الدخول","Edit quota":"تعديل الحصة النسبية","Edit user":"تحرير المستخدم","Edition":"الطبعه","Email":"بريد إلكتروني","Enabled":"تمكين","Failed to create group":"فشل إنشاء مجموعة","Failed to create user":"فشل إنشاء مستخدم","Failed to edit group":"فشل تحرير المجموعة","Failed to edit user":"فشل تحرير المستخدم","Failed to reset logo":"فشل إعادة تعيين الشعار","Failed to upload logo":"فشل تحميل الشعار","Filter groups":"تصفية المجموعات","Filter members":"تصفية الأعضاء","Filter roles":"تصفية الأدوار","Filter:":"تصفيه","First and last name":"الاسم الأول والأخير","First and last name cannot be empty":"لا يمكن أن يكون الاسم الأول واسم العائلة فارغين","First and last name cannot exceed 255 characters":"لا يمكن أن يتجاوز الاسم الأول والأخير 255 حرفا","Forbidden":"ممنوع","General":"عام","Group name":"اسم المجموعة","Group name cannot be empty":"لا يمكن أن يكون اسم المجموعة فارغا","Group name cannot exceed 255 characters":"لا يمكن أن يتجاوز اسم المجموعة 255 حرفا","Group was created successfully":"تم إنشاء المجموعة بنجاح","Groups":"المجموعات","Info":"معلومات","Login":"تسجيل الدخول","Logo":"شعار","Logo was reset successfully. Reloading page...":"تمت إعادة تعيين الشعار بنجاح. إعادة تحميل الصفحة","Logo was uploaded successfully":"تم تحميل الشعار بنجاح","Manager":"مدير","Members":"اعضاء","Modified":"تم التعديل","Name":"اسم","New group":"مجموعة جديدة","New user":"مستخدم جديد","No groups assigned.":"لم يتم تعيين مجموعات","No members found":"لم يتم العثور على أعضاء","No restriction":"لا قيود","No spaces in here":"لا توجد مسافات هنا","No users in here":"لا يوجد مستخدمون هنا","Overview of the information about the selected group":"نظرة عامة على المعلومات حول المجموعة المحددة","Overview of the information about the selected user":"نظرة عامة على المعلومات حول المستخدم المحدد","ownCloud":"السحابة الخاصة","Password":"كلمة المرور","Password cannot be empty":"لا يمكن أن تكون كلمة المرور فارغة","Personal quota":"الحصة الشخصية","Please enter a valid email":"الرجاء إدخال بريد إلكتروني صحيح","Quota":"الحصه النسبيه","Quota will only be applied to users who logged in at least once.":"سيتم تطبيق الحصة النسبية فقط على المستخدمين الذين قاموا بتسجيل الدخول مرة واحدة على الأقل.","Remaining quota":"الحصة المتبقية","Remove from groups":"إزالة من المجموعات","Reset logo":"إعادة تعيين الشعار","Role":"دور","Roles":"ادوار","Search":"بحث","Select a group to view details":"حدد مجموعة لعرض التفاصيل","Select a user to view details":"حدد مستخدما لعرض التفاصيل","Select all groups":"حدد كل المجموعات","Select all spaces":"حدد كل المسافات","Select all users":"حدد جميع المستخدمين","Select...":"اختار...","Show context menu":"إظهار قائمة السياق","Show details":"اظهر التفاصيل","Spaces":"مسافات","Status":"حالة","The file type is unsupported":"نوع الملف غير معتمد","This group is read-only and can't be edited":"هذه المجموعة للقراءة فقط ولا يمكن تحريرها","To set an individual quota, the user needs to have logged in once.":"لتعيين حصة فردية ، يحتاج المستخدم إلى تسجيل الدخول مرة واحدة.","Total quota":"إجمالي الحصة","Unaffected users":"المستخدمون غير المتأثرين","Upload logo":"تحميل الشعار","Used quota":"الحصة المستخدمة","User name":"اسم المستخدم","User name cannot be empty":"لا يمكن أن يكون اسم المLine truncated
|
||||
@@ -0,0 +1,200 @@
|
||||
<template>
|
||||
<div v-if="canManage" id="discord-login-section">
|
||||
<h2 class="oc-py-s" v-text="$gettext('Discord login')" />
|
||||
<p v-if="loadError" class="discord-load-error" v-text="loadError" />
|
||||
<div v-else-if="loaded" class="discord-login-form">
|
||||
<oc-switch
|
||||
:checked="form.enabled"
|
||||
:label="$gettext('Enable Discord login')"
|
||||
@update:checked="(value: boolean) => (form.enabled = value)"
|
||||
/>
|
||||
<oc-text-input
|
||||
id="discord-client-id"
|
||||
v-model="form.clientId"
|
||||
class="oc-mt-m"
|
||||
:label="$gettext('Client ID')"
|
||||
:error-message="errors.client_id"
|
||||
:fix-message-line="true"
|
||||
/>
|
||||
<oc-text-input
|
||||
id="discord-client-secret"
|
||||
v-model="form.clientSecret"
|
||||
type="password"
|
||||
class="oc-mt-m"
|
||||
:label="$gettext('Client Secret')"
|
||||
:description-message="
|
||||
secretSet ? $gettext('A client secret is stored. Leave this field empty to keep it.') : ''
|
||||
"
|
||||
:error-message="errors.client_secret"
|
||||
:fix-message-line="true"
|
||||
/>
|
||||
<oc-text-input
|
||||
id="discord-guild-id"
|
||||
v-model="form.allowedGuildId"
|
||||
class="oc-mt-m"
|
||||
:label="$gettext('Allowed Discord server ID')"
|
||||
:description-message="$gettext('Only members of this Discord server can log in.')"
|
||||
:error-message="errors.allowed_guild_id"
|
||||
:fix-message-line="true"
|
||||
/>
|
||||
<oc-text-input
|
||||
id="discord-redirect-uri"
|
||||
:model-value="redirectUri"
|
||||
class="oc-mt-m"
|
||||
:disabled="true"
|
||||
:label="$gettext('Redirect URI')"
|
||||
:description-message="
|
||||
$gettext('Register this URL as OAuth2 redirect in the Discord Developer Portal.')
|
||||
"
|
||||
/>
|
||||
<oc-button
|
||||
id="discord-save-btn"
|
||||
class="oc-mt-m"
|
||||
:disabled="saving"
|
||||
@click="save"
|
||||
>
|
||||
{{ $gettext('Save') }}
|
||||
</oc-button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { useGettext } from 'vue3-gettext'
|
||||
import { useAbility, useClientService, useMessages } from '@ownclouders/web-pkg'
|
||||
|
||||
defineOptions({
|
||||
name: 'DiscordSection'
|
||||
})
|
||||
|
||||
export type DiscordSettings = {
|
||||
enabled: boolean
|
||||
client_id: string
|
||||
allowed_guild_id: string
|
||||
client_secret_set: boolean
|
||||
redirect_uri: string
|
||||
}
|
||||
|
||||
type Field = 'client_id' | 'client_secret' | 'allowed_guild_id'
|
||||
|
||||
const SETTINGS_URL = '/oauth2/discord/admin/settings'
|
||||
// Discord IDs (snowflakes) are unsigned 64 bit integers in decimal notation.
|
||||
const snowflake = /^[0-9]{15,21}$/
|
||||
|
||||
const ability = useAbility()
|
||||
const clientService = useClientService()
|
||||
const { showMessage, showErrorMessage } = useMessages()
|
||||
const { $gettext } = useGettext()
|
||||
|
||||
const canManage = computed(() => ability.can('update-all', 'Setting'))
|
||||
|
||||
const loaded = ref(false)
|
||||
const loadError = ref('')
|
||||
const saving = ref(false)
|
||||
const secretSet = ref(false)
|
||||
const redirectUri = ref('')
|
||||
const form = reactive({ enabled: false, clientId: '', clientSecret: '', allowedGuildId: '' })
|
||||
const errors = reactive<Record<Field, string>>({
|
||||
client_id: '',
|
||||
client_secret: '',
|
||||
allowed_guild_id: ''
|
||||
})
|
||||
|
||||
const apply = (s: DiscordSettings) => {
|
||||
form.enabled = !!s.enabled
|
||||
form.clientId = s.client_id || ''
|
||||
form.allowedGuildId = s.allowed_guild_id || ''
|
||||
form.clientSecret = ''
|
||||
secretSet.value = !!s.client_secret_set
|
||||
redirectUri.value = s.redirect_uri || ''
|
||||
}
|
||||
|
||||
const clearErrors = () => {
|
||||
errors.client_id = ''
|
||||
errors.client_secret = ''
|
||||
errors.allowed_guild_id = ''
|
||||
}
|
||||
|
||||
const validate = (): boolean => {
|
||||
clearErrors()
|
||||
const clientId = form.clientId.trim()
|
||||
const guildId = form.allowedGuildId.trim()
|
||||
if (clientId && !snowflake.test(clientId)) {
|
||||
errors.client_id = $gettext('The client ID must be a numeric Discord application ID.')
|
||||
}
|
||||
if (guildId && !snowflake.test(guildId)) {
|
||||
errors.allowed_guild_id = $gettext('The server ID must be a numeric Discord server ID.')
|
||||
}
|
||||
if (form.enabled) {
|
||||
if (!clientId) {
|
||||
errors.client_id = $gettext('The client ID is required to enable Discord login.')
|
||||
}
|
||||
if (!guildId) {
|
||||
errors.allowed_guild_id = $gettext('The server ID is required to enable Discord login.')
|
||||
}
|
||||
if (!secretSet.value && !form.clientSecret.trim()) {
|
||||
errors.client_secret = $gettext('The client secret is required to enable Discord login.')
|
||||
}
|
||||
}
|
||||
return !errors.client_id && !errors.client_secret && !errors.allowed_guild_id
|
||||
}
|
||||
|
||||
const load = async () => {
|
||||
try {
|
||||
const { data } = await clientService.httpAuthenticated.get<DiscordSettings>(SETTINGS_URL)
|
||||
apply(data as DiscordSettings)
|
||||
loaded.value = true
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
loadError.value = $gettext('The Discord login settings could not be loaded.')
|
||||
}
|
||||
}
|
||||
|
||||
const save = async () => {
|
||||
if (!validate()) {
|
||||
return
|
||||
}
|
||||
saving.value = true
|
||||
const body: Record<string, unknown> = {
|
||||
enabled: form.enabled,
|
||||
client_id: form.clientId.trim(),
|
||||
allowed_guild_id: form.allowedGuildId.trim()
|
||||
}
|
||||
if (form.clientSecret.trim()) {
|
||||
body.client_secret = form.clientSecret.trim()
|
||||
}
|
||||
try {
|
||||
const { data } = await clientService.httpAuthenticated.put<DiscordSettings>(SETTINGS_URL, body)
|
||||
apply(data as DiscordSettings)
|
||||
showMessage({ title: $gettext('Discord login settings were saved') })
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
const field = (e as { response?: { data?: { error?: { field?: string } } } })?.response?.data
|
||||
?.error?.field as Field | undefined
|
||||
if (field && field in errors) {
|
||||
errors[field] = $gettext('This value is invalid.')
|
||||
}
|
||||
showErrorMessage({
|
||||
title: $gettext('Failed to save the Discord login settings'),
|
||||
errors: [e as Error]
|
||||
})
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (canManage.value) {
|
||||
load()
|
||||
}
|
||||
})
|
||||
|
||||
defineExpose({ form, errors, secretSet, redirectUri, save })
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.discord-login-form {
|
||||
max-width: 500px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,266 @@
|
||||
<template>
|
||||
<div v-if="canManage" id="registration-section">
|
||||
<h2 class="oc-py-s" v-text="$gettext('Registration')" />
|
||||
<p v-if="loadError" class="registration-load-error" v-text="loadError" />
|
||||
<template v-else-if="loaded">
|
||||
<div class="registration-settings">
|
||||
<oc-switch
|
||||
id="registration-allow"
|
||||
:checked="settings.allow_registration"
|
||||
:label="$gettext('Allow new registrations')"
|
||||
@update:checked="(value: boolean) => update('allow_registration', value)"
|
||||
/>
|
||||
<oc-switch
|
||||
id="registration-allow-web"
|
||||
class="oc-mt-s"
|
||||
:checked="settings.allow_web"
|
||||
:label="$gettext('Allow email/password registration')"
|
||||
@update:checked="(value: boolean) => update('allow_web', value)"
|
||||
/>
|
||||
<oc-switch
|
||||
id="registration-allow-discord"
|
||||
class="oc-mt-s"
|
||||
:checked="settings.allow_discord"
|
||||
:label="$gettext('Allow Discord registration')"
|
||||
@update:checked="(value: boolean) => update('allow_discord', value)"
|
||||
/>
|
||||
<oc-switch
|
||||
id="registration-require-approval"
|
||||
class="oc-mt-s"
|
||||
:checked="settings.require_approval"
|
||||
:label="$gettext('Require admin approval')"
|
||||
@update:checked="(value: boolean) => update('require_approval', value)"
|
||||
/>
|
||||
<p
|
||||
v-if="!settings.allow_registration"
|
||||
class="registration-closed-hint oc-text-muted oc-mt-s"
|
||||
v-text="$gettext('New accounts cannot be created while registrations are closed.')"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<h3 class="oc-mt-l oc-mb-s" v-text="$gettext('Pending approvals')" />
|
||||
<p
|
||||
v-if="!pending.length"
|
||||
class="registration-pending-empty oc-text-muted"
|
||||
v-text="$gettext('No accounts are waiting for approval.')"
|
||||
/>
|
||||
<oc-table-simple v-else class="registration-pending-table">
|
||||
<oc-thead>
|
||||
<oc-tr>
|
||||
<oc-th>{{ $gettext('Username') }}</oc-th>
|
||||
<oc-th>{{ $gettext('Email') }}</oc-th>
|
||||
<oc-th>{{ $gettext('Source') }}</oc-th>
|
||||
<oc-th>{{ $gettext('Requested') }}</oc-th>
|
||||
<oc-th class="oc-invisible-sr">{{ $gettext('Actions') }}</oc-th>
|
||||
</oc-tr>
|
||||
</oc-thead>
|
||||
<oc-tbody>
|
||||
<oc-tr v-for="p in pending" :key="p.user_id" class="registration-pending-row">
|
||||
<oc-td translate="no">{{ p.username }}</oc-td>
|
||||
<oc-td translate="no">{{ p.mail || '-' }}</oc-td>
|
||||
<oc-td>
|
||||
<oc-tag size="small" class="registration-source">{{ sourceLabel(p.source) }}</oc-tag>
|
||||
</oc-td>
|
||||
<oc-td>{{ formatDate(p.requested_at) }}</oc-td>
|
||||
<oc-td>
|
||||
<div class="registration-actions">
|
||||
<oc-button
|
||||
class="registration-approve-btn"
|
||||
size="small"
|
||||
variation="primary"
|
||||
appearance="filled"
|
||||
:disabled="busy.has(p.user_id)"
|
||||
@click="approve(p)"
|
||||
>
|
||||
{{ $gettext('Approve') }}
|
||||
</oc-button>
|
||||
<oc-button
|
||||
class="registration-reject-btn"
|
||||
size="small"
|
||||
variation="danger"
|
||||
:disabled="busy.has(p.user_id)"
|
||||
@click="confirmReject(p)"
|
||||
>
|
||||
{{ $gettext('Reject') }}
|
||||
</oc-button>
|
||||
</div>
|
||||
</oc-td>
|
||||
</oc-tr>
|
||||
</oc-tbody>
|
||||
</oc-table-simple>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { useGettext } from 'vue3-gettext'
|
||||
import {
|
||||
formatDateFromJSDate,
|
||||
useAbility,
|
||||
useClientService,
|
||||
useMessages,
|
||||
useModals
|
||||
} from '@ownclouders/web-pkg'
|
||||
|
||||
defineOptions({
|
||||
name: 'RegistrationSection'
|
||||
})
|
||||
|
||||
export type RegistrationSettings = {
|
||||
allow_registration: boolean
|
||||
allow_web: boolean
|
||||
allow_discord: boolean
|
||||
require_approval: boolean
|
||||
}
|
||||
|
||||
export type PendingUser = {
|
||||
user_id: string
|
||||
username: string
|
||||
display_name?: string
|
||||
mail?: string
|
||||
source: 'web' | 'discord' | string
|
||||
requested_at: string
|
||||
}
|
||||
|
||||
type Key = keyof RegistrationSettings
|
||||
|
||||
const SETTINGS_URL = '/oauth2/discord/admin/registration'
|
||||
const PENDING_URL = '/oauth2/discord/admin/pending'
|
||||
|
||||
const ability = useAbility()
|
||||
const clientService = useClientService()
|
||||
const { showMessage, showErrorMessage } = useMessages()
|
||||
const { dispatchModal } = useModals()
|
||||
const language = useGettext()
|
||||
const { $gettext } = language
|
||||
|
||||
const canManage = computed(() => ability.can('update-all', 'Setting'))
|
||||
|
||||
const loaded = ref(false)
|
||||
const loadError = ref('')
|
||||
const settings = reactive<RegistrationSettings>({
|
||||
allow_registration: false,
|
||||
allow_web: false,
|
||||
allow_discord: false,
|
||||
require_approval: false
|
||||
})
|
||||
const pending = ref<PendingUser[]>([])
|
||||
const busy = reactive(new Set<string>())
|
||||
|
||||
const sourceLabel = (source: string) => {
|
||||
switch (source) {
|
||||
case 'web':
|
||||
return $gettext('Web')
|
||||
case 'discord':
|
||||
return $gettext('Discord')
|
||||
default:
|
||||
return source
|
||||
}
|
||||
}
|
||||
|
||||
const formatDate = (iso: string) => {
|
||||
const d = new Date(iso)
|
||||
if (!iso || isNaN(d.getTime())) {
|
||||
return '-'
|
||||
}
|
||||
return formatDateFromJSDate(d, language.current)
|
||||
}
|
||||
|
||||
const load = async () => {
|
||||
try {
|
||||
const [s, p] = await Promise.all([
|
||||
clientService.httpAuthenticated.get<RegistrationSettings>(SETTINGS_URL),
|
||||
clientService.httpAuthenticated.get<{ value: PendingUser[] }>(PENDING_URL)
|
||||
])
|
||||
Object.assign(settings, s.data)
|
||||
pending.value = (p.data as { value?: PendingUser[] })?.value || []
|
||||
loaded.value = true
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
loadError.value = $gettext('The registration settings could not be loaded.')
|
||||
}
|
||||
}
|
||||
|
||||
const update = async (key: Key, value: boolean) => {
|
||||
const previous = settings[key]
|
||||
settings[key] = value
|
||||
try {
|
||||
const { data } = await clientService.httpAuthenticated.put<RegistrationSettings>(
|
||||
SETTINGS_URL,
|
||||
{ ...settings }
|
||||
)
|
||||
Object.assign(settings, data)
|
||||
showMessage({ title: $gettext('Registration settings were saved') })
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
settings[key] = previous
|
||||
showErrorMessage({
|
||||
title: $gettext('Failed to save the registration settings'),
|
||||
errors: [e as Error]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const decide = async (p: PendingUser, action: 'approve' | 'reject') => {
|
||||
busy.add(p.user_id)
|
||||
try {
|
||||
await clientService.httpAuthenticated.post(
|
||||
`${PENDING_URL}/${encodeURIComponent(p.user_id)}/${action}`
|
||||
)
|
||||
pending.value = pending.value.filter((u) => u.user_id !== p.user_id)
|
||||
showMessage({
|
||||
title:
|
||||
action === 'approve'
|
||||
? $gettext('Account "%{user}" was approved', { user: p.username })
|
||||
: $gettext('Account "%{user}" was rejected', { user: p.username })
|
||||
})
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
showErrorMessage({
|
||||
title:
|
||||
action === 'approve'
|
||||
? $gettext('Failed to approve account "%{user}"', { user: p.username })
|
||||
: $gettext('Failed to reject account "%{user}"', { user: p.username }),
|
||||
errors: [e as Error]
|
||||
})
|
||||
} finally {
|
||||
busy.delete(p.user_id)
|
||||
}
|
||||
}
|
||||
|
||||
const approve = (p: PendingUser) => decide(p, 'approve')
|
||||
const reject = (p: PendingUser) => decide(p, 'reject')
|
||||
|
||||
const confirmReject = (p: PendingUser) => {
|
||||
dispatchModal({
|
||||
variation: 'danger',
|
||||
title: $gettext('Reject account "%{user}"?', { user: p.username }),
|
||||
confirmText: $gettext('Reject'),
|
||||
message: $gettext('The account will be deleted. This cannot be undone.'),
|
||||
hasInput: false,
|
||||
onConfirm: () => reject(p)
|
||||
})
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (canManage.value) {
|
||||
load()
|
||||
}
|
||||
})
|
||||
|
||||
defineExpose({ settings, pending, update, approve, reject, confirmReject })
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.registration-settings {
|
||||
max-width: 500px;
|
||||
}
|
||||
|
||||
.registration-actions {
|
||||
display: flex;
|
||||
gap: var(--oc-space-xsmall);
|
||||
justify-content: flex-end;
|
||||
white-space: nowrap;
|
||||
}
|
||||
</style>
|
||||
Loaded 100 of 143 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user