Compare commits
36
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
daf4d1b4db | ||
|
|
22994e6d6d | ||
|
|
45474237d4 | ||
|
|
0968ff11e1 | ||
|
|
620a94abf9 | ||
|
|
fe1c0b6316 | ||
|
|
69a8aee5e9 | ||
|
|
73f975ede5 | ||
|
|
a78bc828b8 | ||
|
|
6be26416f3 | ||
|
|
1b7c258ffd | ||
|
|
347cf8f1c1 | ||
|
|
b06db6ec8f | ||
|
|
870a0ad3f5 | ||
|
|
520326c9ed | ||
|
|
91f0671153 | ||
|
|
898f89c697 | ||
|
|
b708076e67 | ||
|
|
8dc7afc07c | ||
|
|
7dcc74c3dd | ||
|
|
e70497b49c | ||
|
|
b395d08db6 | ||
|
|
1d16dd9e1e | ||
|
|
86fa96362a | ||
|
|
f005d68eae | ||
|
|
d68b53c6d8 | ||
|
|
f8b861c723 | ||
|
|
8b675b2e51 | ||
|
|
34b2b14171 | ||
|
|
9f72d77bfc | ||
|
|
30009ff770 | ||
|
|
d5165c7e48 | ||
|
|
50141f471b | ||
|
|
d65f3fc215 | ||
|
|
1256793012 | ||
|
|
26fa954329 |
No files matched your search
@@ -4,3 +4,9 @@
|
||||
|
||||
CVE-2026-32284 # github.com/shamaton/msgpack/v2 v2.4.0 — no fix available upstream
|
||||
vendor/github.com/crewjam/saml/xmlenc/fuzz.go # test RSA key used in fuzz corpus, not a real secret
|
||||
|
||||
# web frontend transitive dependencies, both pulled in via the pnpm overrides in
|
||||
# web/package.json. Published after the last lockfile refresh, so every branch
|
||||
# fails on them. Drop these once the overrides are bumped upstream.
|
||||
CVE-2026-69152 # brace-expansion 5.0.8 — fix in 5.0.9
|
||||
CVE-2026-18446 # fast-uri 3.1.4 — fix in 3.1.5
|
||||
@@ -0,0 +1,15 @@
|
||||
Bugfix: Prevent deleting your own account in the user management
|
||||
|
||||
In the admin settings user management, the account you are currently logged in
|
||||
as could be selected and included in a delete action, even though the backend
|
||||
always rejects self-deletion. Deleting a selection that included your own
|
||||
account produced a "Failed to delete 1 user" error and made your own row
|
||||
temporarily disappear from the list until the page was refreshed.
|
||||
|
||||
The delete action now excludes the current user from the request, so all other
|
||||
selected users are deleted while your own account is left untouched. When your
|
||||
own account is part of the selection, the delete confirmation dialog shows a
|
||||
hint that it will not be deleted.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/12657
|
||||
https://github.com/owncloud/ocis/issues/12582
|
||||
@@ -0,0 +1,10 @@
|
||||
Bugfix: Stop breadcrumb items from being announced twice
|
||||
|
||||
Each breadcrumb list item had `tabindex="0"`, putting the item itself in the
|
||||
keyboard/screen reader focus order in addition to the link or button nested
|
||||
inside it. This caused every breadcrumb segment to be announced twice in a
|
||||
row. The list item is no longer a separate focus stop; only its inner link
|
||||
or button is, while the item remains focusable enough for existing
|
||||
drag-and-drop styling to keep working.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/12643
|
||||
@@ -0,0 +1,12 @@
|
||||
Bugfix: Announce IDP sign-in errors and fix keyboard use
|
||||
|
||||
The login, consent, and account chooser pages did not announce error
|
||||
messages when they appeared, and invalid username/password fields gave no
|
||||
indication of their error state. The consent screen's scope list also had no
|
||||
programmatic link between each entry and its checkbox, and the account
|
||||
chooser's "continue as" and "use another account" entries could not be
|
||||
reached or activated with a keyboard. A visible focus outline on the login
|
||||
form's input fields had also been removed with no replacement. All of these
|
||||
have been fixed.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/12649
|
||||
@@ -0,0 +1,28 @@
|
||||
Bugfix: Fix low-contrast form controls in dark and vault themes
|
||||
|
||||
Several form controls were hard to see against dark and vault theme
|
||||
backgrounds. The view-options range slider had no visible track border and
|
||||
relied on an opacity dip on hover, making it barely visible at rest. The
|
||||
switch component's off-state track and thumb, and its on-state thumb, used
|
||||
colors too close to their surrounding background to read as a toggle. The
|
||||
select combobox's highlighted/selected option text used a color too close to
|
||||
the highlight background.
|
||||
|
||||
The global search input's text color was forced with `!important`,
|
||||
overriding the theme-specific search text color some themes set, which made
|
||||
typed text render in white on a white search input background in the vault
|
||||
"Dark Theme – High Contrast". The search placeholder color also used an
|
||||
invalid CSS custom property fallback (a bare property name instead of a
|
||||
nested `var()`), silently breaking the placeholder color for any theme that
|
||||
didn't define a search-specific placeholder token, and the vault "Dark
|
||||
Theme"'s placeholder color was too close to its input's text and border color
|
||||
to read as muted.
|
||||
|
||||
The slider now has a visible border and no longer dims on rest, the switch
|
||||
and select now use colors with sufficient contrast against their
|
||||
backgrounds, the `!important` override blocking theme-specific search colors
|
||||
has been removed, the invalid placeholder fallback has been fixed, and the
|
||||
vault "Dark Theme" placeholder color has been changed to one with visible
|
||||
contrast against the input text.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/12639
|
||||
@@ -0,0 +1,9 @@
|
||||
Bugfix: Fix keyboard navigation in "New" and "Upload" dropdown menus
|
||||
|
||||
Opening the "New" or "Upload" dropdown menu in the Files app toolbar did
|
||||
not move focus into the menu, so pressing the arrow keys had no effect
|
||||
on the highlighted item, unlike the existing right-click context menu.
|
||||
Both dropdowns now focus their first item on open, restoring arrow key
|
||||
navigation.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/12646
|
||||
@@ -0,0 +1,10 @@
|
||||
Bugfix: Remove unneeded keyboard focus stops
|
||||
|
||||
Some icons and date columns in tables (spaces list, file list) could
|
||||
unexpectedly receive keyboard focus even though they don't trigger any
|
||||
action, adding unnecessary stops when tabbing through the page. The
|
||||
contextual helper icon also carried a label that duplicated the label
|
||||
already present on its surrounding button. These redundant focus stops
|
||||
and duplicate labels have been removed.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/12645
|
||||
@@ -0,0 +1,9 @@
|
||||
Bugfix: Fix share metadata corruption during concurrent share operations
|
||||
|
||||
When multiple sharing service replicas processed share operations concurrently
|
||||
for the same user, the share metadata could become corrupted with references to
|
||||
missing data, making all shares inaccessible to that user. The received share
|
||||
cache now uses compare-and-swap (etag) validation to detect concurrent writes
|
||||
and retries gracefully, preventing metadata corruption.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/12621
|
||||
@@ -0,0 +1,12 @@
|
||||
Bugfix: Preserve accessibility focus in the file versions sidebar
|
||||
|
||||
Opening the file versions panel with a keyboard or screen reader could move
|
||||
focus to the main page, and restoring a version could briefly move focus to the
|
||||
main page before selecting the sidebar's back button. The sidebar now manages
|
||||
focus throughout panel transitions and loading states, restores focus to the
|
||||
control that opened it when closed, and returns focus to the restored version's
|
||||
Restore button after the operation completes. Version dates and action labels
|
||||
also provide clearer context for screen reader users without duplicate
|
||||
announcements or additional tab stops.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/12630
|
||||
@@ -0,0 +1,10 @@
|
||||
Enhancement: Improve page structure on several pages
|
||||
|
||||
We've added missing `main` and `footer` regions to several pages (404,
|
||||
private link resolving, missing config, logout, access denied, public link
|
||||
resolving) for a more consistent page structure. We've also fixed the
|
||||
"Skip to main" link, which previously did nothing on pages using the plain
|
||||
layout (login, logout, public/private link pages) due to a missing target id
|
||||
and a stale cached DOM reference.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/12637
|
||||
@@ -0,0 +1,7 @@
|
||||
Enhancement: Show the select-all checkbox label in tile view
|
||||
|
||||
The label of the select-all checkbox in the resource tiles view is now
|
||||
visible, improving the user experience by making it clear what the
|
||||
checkbox is for.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/12640
|
||||
@@ -0,0 +1,12 @@
|
||||
Enhancement: Add "Undo" action to the delete success notification
|
||||
|
||||
Deleting a file or folder now shows an "Undo" action alongside the
|
||||
"moved to trash bin" notification, letting users restore the deleted
|
||||
resources directly from the toast instead of navigating to the trash
|
||||
bin. The action is only shown when the resources can be resolved in
|
||||
the trash and the space supports restoring from it. The notification
|
||||
pauses its auto-dismiss timer while hovered or focused, so it does not
|
||||
disappear before the action can be used. Pressing Ctrl+Z (or Cmd+Z on
|
||||
macOS) while the notification is visible triggers the same undo.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/12650
|
||||
@@ -0,0 +1,13 @@
|
||||
Bugfix: Return correct issuerAssignedId on /me
|
||||
|
||||
The `/graph/v1.0/me` endpoint reported the internal user UUID as
|
||||
`identities[].issuerAssignedId` instead of the issuer-assigned identity (the
|
||||
OIDC `sub`). The endpoint took a fast path that built the user model from the
|
||||
CS3 user in the request context, which does not carry the external identity, so
|
||||
it fell back to the internal UUID. `/me` now always resolves the user through
|
||||
the identity backend, which reads the stored external identity and returns the
|
||||
correct value. Group memberships are still only expanded when
|
||||
`$expand=memberOf` is requested.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/12431
|
||||
https://github.com/owncloud/ocis/pull/12411
|
||||
@@ -1,5 +0,0 @@
|
||||
Security: Bump golang.org/x/text to v0.39.0
|
||||
|
||||
We bumped golang.org/x/text to v0.39.0 to address GO-2026-5970, an infinite loop
|
||||
on invalid input. This unblocks the govulncheck CI check, which fails on fixable
|
||||
vulnerabilities.
|
||||
@@ -2,7 +2,7 @@
|
||||
printenv
|
||||
# replace oCIS domain in keycloak realm import
|
||||
mkdir /opt/keycloak/data/import
|
||||
sed -e "s/ocis.owncloud.test/${OCIS_DOMAIN}/g" /opt/keycloak/data/import-dist/ocis-realm.json > /opt/keycloak/data/import/oCIS-realm.json
|
||||
sed -e "s/ocis.owncloud.test/${OCIS_DOMAIN}/g" -e "s/ocis.ocm.owncloud.test/${OCIS_OCM_DOMAIN}/g" /opt/keycloak/data/import-dist/ocis-realm.json > /opt/keycloak/data/import/oCIS-realm.json
|
||||
# sed -e "s/ocis.ocm.owncloud.test/${OCIS_OCM_DOMAIN}/g" /opt/keycloak/data/import-dist/ocis-realm.json > /opt/keycloak/data/import/oCIS-realm.json
|
||||
|
||||
# run original docker-entrypoint
|
||||
|
||||
@@ -192,7 +192,8 @@ services:
|
||||
OCIS_LDAP_BIND_PASSWORD: ${LDAP_ADMIN_PASSWORD:-admin}
|
||||
OCIS_LDAP_GROUP_BASE_DN: "ou=groups,dc=owncloud,dc=com"
|
||||
GRAPH_LDAP_GROUP_CREATE_BASE_DN: "ou=groups-8d24cb5f-6ee6-4b98-86df-c4c268dddb46,ou=groups,dc=owncloud,dc=com"
|
||||
OCIS_LDAP_GROUP_OBJECTCLASS: "owncloudGroup"
|
||||
OCIS_LDAP_GROUP_OBJECTCLASS: "groupOfNames"
|
||||
OCIS_LDAP_GROUP_ADDITIONAL_OBJECTCLASSES: "ownCloudGroup"
|
||||
OCIS_LDAP_USER_BASE_DN: "ou=users,dc=owncloud,dc=com"
|
||||
OCIS_LDAP_USER_OBJECTCLASS: "inetOrgPerson"
|
||||
LDAP_LOGIN_ATTRIBUTES: "uid"
|
||||
@@ -272,6 +273,7 @@ services:
|
||||
- "./config/keycloak/ocis-realm.dist.json:/opt/keycloak/data/import-dist/ocis-realm.json"
|
||||
environment:
|
||||
OCIS_DOMAIN: ${OCIS_DOMAIN:-ocis.owncloud.test}
|
||||
OCIS_OCM_DOMAIN: ${OCIS_OCM_DOMAIN:-ocis.ocm.owncloud.test}
|
||||
KC_HOSTNAME: ${KEYCLOAK_DOMAIN:-keycloak.owncloud.test}
|
||||
KC_DB: postgres
|
||||
KC_DB_URL: "jdbc:postgresql://postgres:5432/keycloak"
|
||||
|
||||
@@ -10,10 +10,10 @@ require (
|
||||
github.com/MicahParks/keyfunc/v2 v2.1.0
|
||||
github.com/Nerzal/gocloak/v13 v13.9.0
|
||||
github.com/bbalet/stopwords v1.0.0
|
||||
github.com/beevik/etree v1.6.0
|
||||
github.com/beevik/etree v1.7.0
|
||||
github.com/blevesearch/bleve/v2 v2.6.0
|
||||
github.com/cenkalti/backoff v2.2.1+incompatible
|
||||
github.com/coreos/go-oidc/v3 v3.19.0
|
||||
github.com/coreos/go-oidc/v3 v3.20.0
|
||||
github.com/cs3org/go-cs3apis v0.0.0-20241105092511-3ad35d174fc1
|
||||
github.com/davidbyttow/govips/v2 v2.18.0
|
||||
github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8
|
||||
@@ -21,10 +21,10 @@ require (
|
||||
github.com/egirna/icap-client v0.1.1
|
||||
github.com/gabriel-vasile/mimetype v1.4.13
|
||||
github.com/ggwhite/go-masker v1.1.0
|
||||
github.com/go-chi/chi/v5 v5.3.0
|
||||
github.com/go-chi/chi/v5 v5.3.1
|
||||
github.com/go-chi/httprate v0.16.0
|
||||
github.com/go-chi/render v1.0.3
|
||||
github.com/go-ldap/ldap/v3 v3.4.13
|
||||
github.com/go-ldap/ldap/v3 v3.4.14
|
||||
github.com/go-ldap/ldif v0.0.0-20200320164324-fd88d9b715b3
|
||||
github.com/go-micro/plugins/v4/client/grpc v1.2.1
|
||||
github.com/go-micro/plugins/v4/logger/zerolog v1.2.0
|
||||
@@ -50,7 +50,7 @@ require (
|
||||
github.com/jellydator/ttlcache/v3 v3.4.1
|
||||
github.com/jinzhu/now v1.1.5
|
||||
github.com/justinas/alice v1.2.0
|
||||
github.com/kovidgoyal/imaging v1.8.22
|
||||
github.com/kovidgoyal/imaging v1.8.23
|
||||
github.com/leonelquinteros/gotext v1.7.2
|
||||
github.com/libregraph/idm v0.5.0
|
||||
github.com/libregraph/lico v0.67.0
|
||||
@@ -66,10 +66,10 @@ require (
|
||||
github.com/open-policy-agent/opa v1.18.2
|
||||
github.com/orcaman/concurrent-map v1.0.0
|
||||
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260710104539-1f85e04c1e35
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260804082450-45ec3bf8ba7c
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/pkg/xattr v0.4.12
|
||||
github.com/prometheus/client_golang v1.23.2
|
||||
github.com/prometheus/client_golang v1.24.1
|
||||
github.com/r3labs/sse/v2 v2.10.0
|
||||
github.com/rogpeppe/go-internal v1.15.0
|
||||
github.com/rs/cors v1.11.1
|
||||
@@ -96,16 +96,16 @@ require (
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.44.0
|
||||
go.opentelemetry.io/otel/sdk v1.44.0
|
||||
go.opentelemetry.io/otel/trace v1.44.0
|
||||
golang.org/x/crypto v0.53.0
|
||||
golang.org/x/crypto v0.54.0
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f
|
||||
golang.org/x/image v0.43.0
|
||||
golang.org/x/net v0.56.0
|
||||
golang.org/x/image v0.44.0
|
||||
golang.org/x/net v0.57.0
|
||||
golang.org/x/oauth2 v0.36.0
|
||||
golang.org/x/sync v0.21.0
|
||||
golang.org/x/term v0.44.0
|
||||
golang.org/x/text v0.39.0
|
||||
golang.org/x/sync v0.22.0
|
||||
golang.org/x/term v0.45.0
|
||||
golang.org/x/text v0.40.0
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa
|
||||
google.golang.org/grpc v1.82.0
|
||||
google.golang.org/grpc v1.82.1
|
||||
google.golang.org/protobuf v1.36.11
|
||||
gopkg.in/yaml.v2 v2.4.0
|
||||
gotest.tools/v3 v3.5.2
|
||||
@@ -186,7 +186,7 @@ require (
|
||||
github.com/fsnotify/fsnotify v1.10.1 // indirect
|
||||
github.com/gdexlab/go-render v1.0.1 // indirect
|
||||
github.com/go-acme/lego/v4 v4.34.0 // indirect
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8-0.20250403174932-29230038a667 // indirect
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8 // indirect
|
||||
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect
|
||||
github.com/go-git/go-billy/v5 v5.9.0 // indirect
|
||||
github.com/go-git/go-git/v5 v5.19.1 // indirect
|
||||
@@ -240,7 +240,7 @@ require (
|
||||
github.com/json-iterator/go v1.1.13-0.20220915233716-71ac16282d12 // indirect
|
||||
github.com/juliangruber/go-intersect v1.1.0 // indirect
|
||||
github.com/kevinburke/ssh_config v1.2.0 // indirect
|
||||
github.com/klauspost/compress v1.18.6 // indirect
|
||||
github.com/klauspost/compress v1.19.1 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||
github.com/klauspost/crc32 v1.3.0 // indirect
|
||||
github.com/kovidgoyal/go-parallel v1.1.1 // indirect
|
||||
@@ -260,7 +260,7 @@ require (
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.21 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.23 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.47 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.48 // indirect
|
||||
github.com/maxymania/go-system v0.0.0-20170110133659-647cc364bf0b // indirect
|
||||
github.com/mendsley/gojwk v0.0.0-20141217222730-4d5ec6e58103 // indirect
|
||||
github.com/miekg/dns v1.1.72 // indirect
|
||||
@@ -295,8 +295,8 @@ require (
|
||||
github.com/pquerna/cachecontrol v0.2.0 // indirect
|
||||
github.com/prometheus/alertmanager v0.33.1 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
github.com/prometheus/common v0.67.5 // indirect
|
||||
github.com/prometheus/procfs v0.20.1 // indirect
|
||||
github.com/prometheus/common v0.70.1 // indirect
|
||||
github.com/prometheus/procfs v0.21.1 // indirect
|
||||
github.com/prometheus/statsd_exporter v0.22.8 // indirect
|
||||
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 // indirect
|
||||
github.com/rs/xid v1.6.0 // indirect
|
||||
@@ -308,7 +308,7 @@ require (
|
||||
github.com/segmentio/ksuid v1.0.4 // indirect
|
||||
github.com/sercand/kuberesolver/v5 v5.1.1 // indirect
|
||||
github.com/sergi/go-diff v1.4.0 // indirect
|
||||
github.com/sethvargo/go-password v0.3.1 // indirect
|
||||
github.com/sethvargo/go-password v0.4.0 // indirect
|
||||
github.com/skeema/knownhosts v1.3.1 // indirect
|
||||
github.com/spacewander/go-suffix-tree v0.0.0-20191010040751-0865e368c784 // indirect
|
||||
github.com/spf13/pflag v1.0.10 // indirect
|
||||
@@ -338,11 +338,11 @@ require (
|
||||
go.opentelemetry.io/otel/metric v1.44.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.10.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap v1.27.0 // indirect
|
||||
go.uber.org/zap v1.27.1 // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.4 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/mod v0.37.0 // indirect
|
||||
golang.org/x/sys v0.46.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
golang.org/x/tools v0.47.0 // indirect
|
||||
google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 // indirect
|
||||
|
||||
@@ -104,8 +104,8 @@ github.com/aws/aws-sdk-go v1.55.8 h1:JRmEUbU52aJQZ2AjX4q4Wu7t4uZjOu71uyNmaWlUkJQ
|
||||
github.com/aws/aws-sdk-go v1.55.8/go.mod h1:ZkViS9AqA6otK+JBBNH2++sx1sgxrPKcSzPPvQkUtXk=
|
||||
github.com/bbalet/stopwords v1.0.0 h1:0TnGycCtY0zZi4ltKoOGRFIlZHv0WqpoIGUsObjztfo=
|
||||
github.com/bbalet/stopwords v1.0.0/go.mod h1:sAWrQoDMfqARGIn4s6dp7OW7ISrshUD8IP2q3KoqPjc=
|
||||
github.com/beevik/etree v1.6.0 h1:u8Kwy8pp9D9XeITj2Z0XtA5qqZEmtJtuXZRQi+j03eE=
|
||||
github.com/beevik/etree v1.6.0/go.mod h1:bh4zJxiIr62SOf9pRzN7UUYaEDa9HEKafK25+sLc0Gc=
|
||||
github.com/beevik/etree v1.7.0 h1:xjBk9O4p4x7D1YajePjfLzdaFC4/uYUENA7P0pv6gXA=
|
||||
github.com/beevik/etree v1.7.0/go.mod h1:bh4zJxiIr62SOf9pRzN7UUYaEDa9HEKafK25+sLc0Gc=
|
||||
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
|
||||
github.com/beorn7/perks v0.0.0-20160804104726-4c0e84591b9a/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
|
||||
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
|
||||
@@ -188,8 +188,8 @@ github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJ
|
||||
github.com/cloudflare/circl v1.6.3 h1:9GPOhQGF9MCYUeXyMYlqTR6a5gTrgR/fBLXvUgtVcg8=
|
||||
github.com/cloudflare/circl v1.6.3/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4=
|
||||
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
|
||||
github.com/coreos/go-oidc/v3 v3.19.0 h1:F/xyOi3x1UnG1U27YVnM1N6bHiL1K2upi6U/0qr8r+I=
|
||||
github.com/coreos/go-oidc/v3 v3.19.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
|
||||
github.com/coreos/go-oidc/v3 v3.20.0 h1:EtE0WIBHk03N+DqGkY4+UONzzZHk7amKt6IyNd7OsZE=
|
||||
github.com/coreos/go-oidc/v3 v3.20.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
|
||||
github.com/coreos/go-semver v0.3.1 h1:yi21YpKnrx1gt5R+la8n5WgS0kCrsPp33dmEyHReZr4=
|
||||
github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03VsM8rvUec=
|
||||
github.com/coreos/go-systemd/v22 v22.7.0 h1:LAEzFkke61DFROc7zNLX/WA2i5J8gYqe0rSj9KI28KA=
|
||||
@@ -286,10 +286,10 @@ github.com/go-acme/lego/v4 v4.34.0 h1:oRsIuPJ4ORX7ufviXvelUpBSez2XxeKGwo5pNG9BVe
|
||||
github.com/go-acme/lego/v4 v4.34.0/go.mod h1:gsmdlx/ZS6OUeXbOj0U+VnCLLfEFj4WCYRkcGpZw+pc=
|
||||
github.com/go-asn1-ber/asn1-ber v1.3.1/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
||||
github.com/go-asn1-ber/asn1-ber v1.4.1/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8-0.20250403174932-29230038a667 h1:BP4M0CvQ4S3TGls2FvczZtj5Re/2ZzkV9VwqPHH/3Bo=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8-0.20250403174932-29230038a667/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
||||
github.com/go-chi/chi/v5 v5.3.0 h1:halUjDxhshgXHMrao5bB8eNBXo/rnzwr8m5m36glehM=
|
||||
github.com/go-chi/chi/v5 v5.3.0/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8 h1:H9AZkK22UOmfX8J84ubyaZxKJZ3FMHVwn8swoMML7iQ=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
||||
github.com/go-chi/chi/v5 v5.3.1 h1:3j4HZLGZQ3JpMCrPJF/Jl3mYJfWLKBfNJ6quurUGCf8=
|
||||
github.com/go-chi/chi/v5 v5.3.1/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
|
||||
github.com/go-chi/httprate v0.16.0 h1:8V5DH9j6pSK6UQoBsTpvMyFxycqaKEIToyPKzHJjUa8=
|
||||
github.com/go-chi/httprate v0.16.0/go.mod h1:A8lo+qRhk+s9LiuP5saS7XCGDXRXMcrueq0NfIuCa/I=
|
||||
github.com/go-chi/render v1.0.3 h1:AsXqd2a1/INaIfUSKq3G5uA8weYx20FOsM7uSoCyyt4=
|
||||
@@ -317,8 +317,8 @@ github.com/go-kit/log v0.2.0/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBj
|
||||
github.com/go-kit/log v0.2.1 h1:MRVx0/zhvdseW+Gza6N9rVzU/IVzaeE1SFI4raAhmBU=
|
||||
github.com/go-kit/log v0.2.1/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0=
|
||||
github.com/go-ldap/ldap/v3 v3.1.7/go.mod h1:5Zun81jBTabRaI8lzN7E1JjyEl1g6zI6u9pd8luAK4Q=
|
||||
github.com/go-ldap/ldap/v3 v3.4.13 h1:+x1nG9h+MZN7h/lUi5Q3UZ0fJ1GyDQYbPvbuH38baDQ=
|
||||
github.com/go-ldap/ldap/v3 v3.4.13/go.mod h1:LxsGZV6vbaK0sIvYfsv47rfh4ca0JXokCoKjZxsszv0=
|
||||
github.com/go-ldap/ldap/v3 v3.4.14 h1:D6PYdEgsaVzsXyr6w/yDC06Ria4uUhWm+Rb+er8lfAs=
|
||||
github.com/go-ldap/ldap/v3 v3.4.14/go.mod h1:S4eJUMUNjDkE0ZJtIZdybwyb03sGGLW6gxXT1Hs8VKA=
|
||||
github.com/go-ldap/ldif v0.0.0-20200320164324-fd88d9b715b3 h1:sfz1YppV05y4sYaW7kXZtrocU/+vimnIWt4cxAYh7+o=
|
||||
github.com/go-ldap/ldif v0.0.0-20200320164324-fd88d9b715b3/go.mod h1:ZXFhGda43Z2TVbfGZefXyMJzsDHhCh0go3bZUcwTx7o=
|
||||
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
|
||||
@@ -576,8 +576,8 @@ github.com/kevinburke/ssh_config v1.2.0 h1:x584FjTGwHzMwvHx18PXxbBVzfnxogHaAReU4
|
||||
github.com/kevinburke/ssh_config v1.2.0/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM=
|
||||
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
|
||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||
github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=
|
||||
github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
|
||||
github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
@@ -597,8 +597,8 @@ github.com/kovidgoyal/go-parallel v1.1.1 h1:1OzpNjtrUkBPq3UaqrnvOoB2F9RttSt811ui
|
||||
github.com/kovidgoyal/go-parallel v1.1.1/go.mod h1:BJNIbe6+hxyFWv7n6oEDPj3PA5qSw5OCtf0hcVxWJiw=
|
||||
github.com/kovidgoyal/go-shm v1.0.0 h1:HJEel9D1F9YhULvClEHJLawoRSj/1u/EDV7MJbBPgQo=
|
||||
github.com/kovidgoyal/go-shm v1.0.0/go.mod h1:Yzb80Xf9L3kaoB2RGok9hHwMIt7Oif61kT6t3+VnZds=
|
||||
github.com/kovidgoyal/imaging v1.8.22 h1:CtpoRXQpS79xxJsKu8+LUJJE/0i4FLquJZy0QH+QNlM=
|
||||
github.com/kovidgoyal/imaging v1.8.22/go.mod h1:y8wo4JTv4D+skbtQf6fHg8nA1qtagvCcn8J2Nu5k2Jg=
|
||||
github.com/kovidgoyal/imaging v1.8.23 h1:4WsboyQ/E8tic2kX49P93Rvscg33SPsCwTBG5EZZF54=
|
||||
github.com/kovidgoyal/imaging v1.8.23/go.mod h1:k3Iot3H0v2rSWXIxQISfT3e9wIryqzAHLHCuhG7z9lM=
|
||||
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||
@@ -652,8 +652,8 @@ github.com/mattn/go-isatty v0.0.21 h1:xYae+lCNBP7QuW4PUnNG61ffM4hVIfm+zUzDuSzYLG
|
||||
github.com/mattn/go-isatty v0.0.21/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
|
||||
github.com/mattn/go-runewidth v0.0.23 h1:7ykA0T0jkPpzSvMS5i9uoNn2Xy3R383f9HDx3RybWcw=
|
||||
github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
|
||||
github.com/mattn/go-sqlite3 v1.14.47 h1:jOBI62gS7nKeZv+as1oGEy0+1qISgXwH/QBlR6KbfIo=
|
||||
github.com/mattn/go-sqlite3 v1.14.47/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w=
|
||||
github.com/mattn/go-sqlite3 v1.14.48 h1:7XHIgl0a8HwOaiK4E47ozLkST78rR9+OtNGx27D/TFs=
|
||||
github.com/mattn/go-sqlite3 v1.14.48/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
|
||||
github.com/maxymania/go-system v0.0.0-20170110133659-647cc364bf0b h1:Q53idHrTuQDDHyXaxZ6pUl0I9uyD6Z6uKFK3ocX6LzI=
|
||||
github.com/maxymania/go-system v0.0.0-20170110133659-647cc364bf0b/go.mod h1:KirJrATYGbTyUwVR26xIkaipRqRcMRXBf8N5dacvGus=
|
||||
@@ -739,8 +739,16 @@ github.com/orcaman/concurrent-map v1.0.0 h1:I/2A2XPCb4IuQWcQhBhSwGfiuybl/J0ev9HD
|
||||
github.com/orcaman/concurrent-map v1.0.0/go.mod h1:Lu3tH6HLW3feq74c2GC+jIMS/K2CFcDWnWD9XkenwhI=
|
||||
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245 h1:JRidLTAKhnvyLMRtVtSF4lhBa0NSAOs6fof+d6JnKII=
|
||||
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245/go.mod h1:z61VMGAJRtR1nbgXWiNoCkxUXP1B3Je9rMuJbnGd+Og=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260710104539-1f85e04c1e35 h1:40KHez6z6Ea+MHatRfZp4ZTX1TASGRG5UfvOpsQRbgU=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260710104539-1f85e04c1e35/go.mod h1:m2fGRZDsnNSBszbnwysuq7uhlitQ90+weX4FFQRdkak=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260731133734-ff71861a97b3 h1:cx509Tm9QnYvf5OCQs4jwMZgTVMMUjFiVcKmGzmP/r0=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260731133734-ff71861a97b3/go.mod h1:bW0gOn58J6J9sWQDdWP5oQhCjTKoEGAxT4tWE6Ztziw=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260803085958-0f1033fbf237 h1:6EInmwSbEg91zdXQ65/uz21gwC3ZZ9VxlBqpRgT/w3U=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260803085958-0f1033fbf237/go.mod h1:bW0gOn58J6J9sWQDdWP5oQhCjTKoEGAxT4tWE6Ztziw=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260803112253-6c2f84027dda h1:rg+J1SmPVCnt174ytaZHydtHfUyJ9AomdrADpL7dELo=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260803112253-6c2f84027dda/go.mod h1:bW0gOn58J6J9sWQDdWP5oQhCjTKoEGAxT4tWE6Ztziw=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260803123448-40f303ed2d94 h1:Dau8BtnYwOlDJWx0dw3Kz2tcbricrbMIxFsaU32cc1k=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260803123448-40f303ed2d94/go.mod h1:bW0gOn58J6J9sWQDdWP5oQhCjTKoEGAxT4tWE6Ztziw=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260804082450-45ec3bf8ba7c h1:m3HzDJsnHEKcR4J4M/+Al8hSRG8uw35CI3zS7GZx9Nc=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260804082450-45ec3bf8ba7c/go.mod h1:bW0gOn58J6J9sWQDdWP5oQhCjTKoEGAxT4tWE6Ztziw=
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw=
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
|
||||
github.com/pablodz/inotifywaitgo v0.0.12 h1:DVJJTFMDlSAdO46yisPF2vzozs/r+4k6ih8MVghq78M=
|
||||
@@ -780,8 +788,8 @@ github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqr
|
||||
github.com/prometheus/client_golang v1.12.1/go.mod h1:3Z9XVyYiZYEO+YQWt3RD2R3jrbd179Rt297l4aS6nDY=
|
||||
github.com/prometheus/client_golang v1.12.2/go.mod h1:3Z9XVyYiZYEO+YQWt3RD2R3jrbd179Rt297l4aS6nDY=
|
||||
github.com/prometheus/client_golang v1.13.0/go.mod h1:vTeo+zgvILHsnnj/39Ou/1fPN5nJFOEMgftOUOmlvYQ=
|
||||
github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
|
||||
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
|
||||
github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
|
||||
github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
|
||||
github.com/prometheus/client_model v0.0.0-20170216185247-6f3806018612/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
|
||||
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
|
||||
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||
@@ -796,8 +804,8 @@ github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9
|
||||
github.com/prometheus/common v0.32.1/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls=
|
||||
github.com/prometheus/common v0.35.0/go.mod h1:phzohg0JFMnBEFGxTDbfu3QyL5GI8gTQJFhYO5B3mfA=
|
||||
github.com/prometheus/common v0.37.0/go.mod h1:phzohg0JFMnBEFGxTDbfu3QyL5GI8gTQJFhYO5B3mfA=
|
||||
github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4=
|
||||
github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw=
|
||||
github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY=
|
||||
github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
|
||||
github.com/prometheus/procfs v0.0.0-20170703101242-e645f4e5aaa8/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
|
||||
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
|
||||
github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
|
||||
@@ -805,8 +813,8 @@ github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4O
|
||||
github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
|
||||
github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
|
||||
github.com/prometheus/procfs v0.8.0/go.mod h1:z7EfXMXOkbkqb9IINtpCn86r/to3BnA0uaxHdg830/4=
|
||||
github.com/prometheus/procfs v0.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc=
|
||||
github.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo=
|
||||
github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
|
||||
github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
|
||||
github.com/prometheus/statsd_exporter v0.22.7/go.mod h1:N/TevpjkIh9ccs6nuzY3jQn9dFqnUakOjnEuMPJJJnI=
|
||||
github.com/prometheus/statsd_exporter v0.22.8 h1:Qo2D9ZzaQG+id9i5NYNGmbf1aa/KxKbB9aKfMS+Yib0=
|
||||
github.com/prometheus/statsd_exporter v0.22.8/go.mod h1:/DzwbTEaFTE0Ojz5PqcSk6+PFHOPWGxdXVr6yC8eFOM=
|
||||
@@ -839,8 +847,8 @@ github.com/sercand/kuberesolver/v5 v5.1.1 h1:CYH+d67G0sGBj7q5wLK61yzqJJ8gLLC8aep
|
||||
github.com/sercand/kuberesolver/v5 v5.1.1/go.mod h1:Fs1KbKhVRnB2aDWN12NjKCB+RgYMWZJ294T3BtmVCpQ=
|
||||
github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
|
||||
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
|
||||
github.com/sethvargo/go-password v0.3.1 h1:WqrLTjo7X6AcVYfC6R7GtSyuUQR9hGyAj/f1PYQZCJU=
|
||||
github.com/sethvargo/go-password v0.3.1/go.mod h1:rXofC1zT54N7R8K/h1WDUdkf9BOx5OptoxrMBcrXzvs=
|
||||
github.com/sethvargo/go-password v0.4.0 h1:eSidVKQw5C7CmTDAtH3RipBTSjdU1ZRxQaynD2GWLVU=
|
||||
github.com/sethvargo/go-password v0.4.0/go.mod h1:PO3nYHwUpcHPR0F9woy7a4abZPvzRuqJr0GaeIYTm3k=
|
||||
github.com/shamaton/msgpack/v2 v2.4.1 h1:JtJ141QoQ3NqgPDsjq2v9VXlaON8SiQOwEaoNLEK/MQ=
|
||||
github.com/shamaton/msgpack/v2 v2.4.1/go.mod h1:6khjYnkx73f7VQU7wjcFS9DFjs+59naVWJv1TB7qdOI=
|
||||
github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI=
|
||||
@@ -998,8 +1006,8 @@ go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9i
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.uber.org/zap v1.18.1/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI=
|
||||
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
|
||||
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||
go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=
|
||||
go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
|
||||
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
@@ -1015,8 +1023,8 @@ golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0
|
||||
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
|
||||
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
|
||||
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
|
||||
golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
|
||||
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
|
||||
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
||||
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
|
||||
@@ -1031,8 +1039,8 @@ golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f h1:W3F4c+6OLc6H2lb//N1q4WpJk
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f/go.mod h1:J1xhfL/vlindoeF/aINzNzt2Bket5bjo9sdOYzOsU80=
|
||||
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
|
||||
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
||||
golang.org/x/image v0.43.0 h1:FLxcP4ec2350nTfOC8ysKtqYSIFbk/QGjw1ZHNP4tsY=
|
||||
golang.org/x/image v0.43.0/go.mod h1:rrpelvGFt+kLPAjPM4HeWPgrl0FtafueU//e5N0qk/Q=
|
||||
golang.org/x/image v0.44.0 h1:+tDekMZED9+LrtB3G5xzRggpVh9CARjZqROla3R3R+I=
|
||||
golang.org/x/image v0.44.0/go.mod h1:V8K3KE9KKKE+pLpQDOeN18w9oacNSvy1tDOirTu4xtY=
|
||||
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
@@ -1099,8 +1107,8 @@ golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
|
||||
golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
|
||||
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
|
||||
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
|
||||
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
@@ -1124,8 +1132,8 @@ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJ
|
||||
golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
|
||||
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
@@ -1188,8 +1196,8 @@ golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
|
||||
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
@@ -1197,8 +1205,8 @@ golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||
golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U=
|
||||
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
|
||||
golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58=
|
||||
golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc=
|
||||
golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=
|
||||
golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
|
||||
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
|
||||
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
@@ -1210,8 +1218,8 @@ golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=
|
||||
golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
@@ -1343,8 +1351,8 @@ google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3Iji
|
||||
google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
|
||||
google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
|
||||
google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc=
|
||||
google.golang.org/grpc v1.82.0 h1:vguDnZUPjE26w09A63VoxZPnvPjB5Riyc0mkXPFmAIU=
|
||||
google.golang.org/grpc v1.82.0/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA=
|
||||
google.golang.org/grpc v1.82.1 h1:NnAxzGRA0677vCa4BUkOAnO5+FfQqVl9iUXeD0IqcGE=
|
||||
google.golang.org/grpc v1.82.1/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA=
|
||||
google.golang.org/grpc/examples v0.0.0-20211102180624-670c133e568e h1:m7aQHHqd0q89mRwhwS9Bx2rjyl/hsFAeta+uGrHsQaU=
|
||||
google.golang.org/grpc/examples v0.0.0-20211102180624-670c133e568e/go.mod h1:gID3PKrg7pWKntu9Ss6zTLJ0ttC0X9IHgREOCZwbCVU=
|
||||
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
|
||||
|
||||
@@ -62,22 +62,22 @@ func (g Graph) GetMe(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
var me *libregraph.User
|
||||
// We can just return the user from context unless we need to expand the group memberships
|
||||
if !slices.Contains(exp, "memberOf") {
|
||||
me = identity.CreateUserModelFromCS3(u)
|
||||
} else {
|
||||
var err error
|
||||
logger.Debug().Msg("calling get user on backend")
|
||||
me, err = g.identityBackend.GetUser(r.Context(), u.GetId().GetOpaqueId(), odataReq)
|
||||
if err != nil {
|
||||
logger.Debug().Err(err).Interface("user", u).Msg("could not get user from backend")
|
||||
errorcode.RenderError(w, r, err)
|
||||
return
|
||||
}
|
||||
if me.MemberOf == nil {
|
||||
me.MemberOf = []libregraph.Group{}
|
||||
}
|
||||
// Always resolve the user through the identity backend. The CS3 user from
|
||||
// the request context does not carry the issuer-assigned identity (OIDC
|
||||
// sub), so building the model from it (CreateUserModelFromCS3) would report
|
||||
// the internal user UUID as identities[].issuerAssignedId. The backend reads
|
||||
// the stored external identity and returns the correct value. Group
|
||||
// memberships are only expanded (and thus only queried) when $expand=memberOf
|
||||
// is requested, so the extra cost here is a single user lookup.
|
||||
logger.Debug().Msg("calling get user on backend")
|
||||
me, err := g.identityBackend.GetUser(r.Context(), u.GetId().GetOpaqueId(), odataReq)
|
||||
if err != nil {
|
||||
logger.Debug().Err(err).Interface("user", u).Msg("could not get user from backend")
|
||||
errorcode.RenderError(w, r, err)
|
||||
return
|
||||
}
|
||||
if slices.Contains(exp, "memberOf") && me.MemberOf == nil {
|
||||
me.MemberOf = []libregraph.Group{}
|
||||
}
|
||||
|
||||
// expand appRoleAssignments if requested
|
||||
|
||||
@@ -115,6 +115,16 @@ var _ = Describe("Users", func() {
|
||||
})
|
||||
|
||||
It("gets the information", func() {
|
||||
user := &libregraph.User{
|
||||
Id: libregraph.PtrString("user"),
|
||||
Identities: []libregraph.ObjectIdentity{
|
||||
{
|
||||
Issuer: libregraph.PtrString("https://idp.example.com"),
|
||||
IssuerAssignedId: libregraph.PtrString("the-oidc-sub"),
|
||||
},
|
||||
},
|
||||
}
|
||||
identityBackend.On("GetUser", mock.Anything, mock.Anything, mock.Anything).Return(user, nil)
|
||||
valueService.On("GetValueByUniqueIdentifiers", mock.Anything, mock.Anything, mock.Anything).
|
||||
Return(&settings.GetValueResponse{
|
||||
Value: &settingsmsg.ValueWithIdentifier{
|
||||
@@ -139,6 +149,19 @@ var _ = Describe("Users", func() {
|
||||
svc.GetMe(rr, r)
|
||||
|
||||
Expect(rr.Code).To(Equal(http.StatusOK))
|
||||
|
||||
data, err := io.ReadAll(rr.Body)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
responseUser := &libregraph.User{}
|
||||
err = json.Unmarshal(data, &responseUser)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
// The identity (issuerAssignedId, the OIDC sub) must come from the
|
||||
// backend, not be fabricated from the internal user UUID. See
|
||||
// OCISDEV-751.
|
||||
Expect(responseUser.GetIdentities()).To(HaveLen(1))
|
||||
Expect(responseUser.GetIdentities()[0].GetIssuerAssignedId()).To(Equal("the-oidc-sub"))
|
||||
})
|
||||
|
||||
It("expands the memberOf", func() {
|
||||
@@ -193,6 +216,10 @@ var _ = Describe("Users", func() {
|
||||
RoleId: "some-appRole-ID",
|
||||
},
|
||||
}
|
||||
user := &libregraph.User{
|
||||
Id: libregraph.PtrString("user"),
|
||||
}
|
||||
identityBackend.On("GetUser", mock.Anything, mock.Anything, mock.Anything).Return(user, nil)
|
||||
roleService.On("ListRoleAssignments", mock.Anything, mock.Anything, mock.Anything).Return(&settings.ListRoleAssignmentsResponse{Assignments: assignments}, nil)
|
||||
valueService.On("GetValueByUniqueIdentifiers", mock.Anything, mock.Anything, mock.Anything).
|
||||
Return(&settings.GetValueResponse{
|
||||
|
||||
@@ -14,16 +14,16 @@
|
||||
<div class="oc-login-form" id="chooseaccount-root">
|
||||
<img class="oc-logo" src="{{.LogoURL}}" alt="ownCloud">
|
||||
<h1 class="oc-invisible-sr">{{.Headline}}</h1>
|
||||
<p id="oc-chooseaccount-error" class="oc-error-message" hidden></p>
|
||||
<p id="oc-chooseaccount-error" class="oc-error-message" role="alert" aria-live="assertive" hidden></p>
|
||||
<div id="chooseaccount-body" hidden>
|
||||
<p class="oc-light oc-consent-headline" id="chooseaccount-title">{{.HeadlineSub}}</p>
|
||||
<ul class="oc-consent-scopes" id="account-list">
|
||||
<li class="oc-chooseaccount-item" id="item-current">
|
||||
<span class="oc-chooseaccount-avatar" id="avatar-current"></span>
|
||||
<li class="oc-chooseaccount-item" id="item-current" role="button" tabindex="0">
|
||||
<span class="oc-chooseaccount-avatar" id="avatar-current" aria-hidden="true"></span>
|
||||
<span class="oc-light oc-chooseaccount-label" id="label-current"></span>
|
||||
</li>
|
||||
<li class="oc-chooseaccount-item" id="item-other">
|
||||
<span class="oc-chooseaccount-avatar">?</span>
|
||||
<li class="oc-chooseaccount-item" id="item-other" role="button" tabindex="0">
|
||||
<span class="oc-chooseaccount-avatar" aria-hidden="true">?</span>
|
||||
<span class="oc-light oc-chooseaccount-label">{{.UseAnotherLabel}}</span>
|
||||
</li>
|
||||
</ul>
|
||||
@@ -77,6 +77,15 @@
|
||||
catch (_) { return false; }
|
||||
}
|
||||
|
||||
function onKeyActivate(el, handler) {
|
||||
el.addEventListener("keydown", function(e) {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault();
|
||||
handler();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
var helloReq = {
|
||||
state: qs("state"),
|
||||
flow: qs("flow") || "oidc",
|
||||
@@ -106,7 +115,7 @@
|
||||
bodyEl.hidden = false;
|
||||
|
||||
// "Continue as current user" — mode=0 logon (cookie re-auth, no password)
|
||||
itemCurrent.addEventListener("click", function() {
|
||||
function activateCurrent() {
|
||||
itemCurrent.style.opacity = "0.5";
|
||||
itemOther.style.pointerEvents = "none";
|
||||
fetchApi("/_/logon", { state: helloReq.state, params: [data.username, "", "0"], hello: helloReq })
|
||||
@@ -133,14 +142,16 @@
|
||||
resetSignInState();
|
||||
})
|
||||
.catch(resetSignInState);
|
||||
});
|
||||
}
|
||||
itemCurrent.addEventListener("click", activateCurrent);
|
||||
onKeyActivate(itemCurrent, activateCurrent);
|
||||
})
|
||||
.catch(function() {
|
||||
window.location.href = pathPrefix + '/identifier' + window.location.search;
|
||||
});
|
||||
|
||||
// "Use another account" — invalidate current session then go to login form
|
||||
itemOther.addEventListener("click", function() {
|
||||
function activateOther() {
|
||||
var loginParams = new URLSearchParams(window.location.search);
|
||||
loginParams.set("prompt", "login");
|
||||
loginParams.delete("flow");
|
||||
@@ -148,7 +159,9 @@
|
||||
fetchApi("/_/logoff", { state: helloReq.state }).then(function() {
|
||||
window.location.href = target;
|
||||
});
|
||||
});
|
||||
}
|
||||
itemOther.addEventListener("click", activateOther);
|
||||
onKeyActivate(itemOther, activateOther);
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
<div class="oc-login-form" id="consent-root">
|
||||
<img class="oc-logo" src="{{.LogoURL}}" alt="ownCloud">
|
||||
<h1 class="oc-invisible-sr">{{.Headline}}</h1>
|
||||
<p id="oc-consent-error-message" class="oc-error-message" hidden></p>
|
||||
<p id="oc-consent-error-message" class="oc-error-message" role="alert" aria-live="assertive" hidden></p>
|
||||
<div id="consent-body" hidden>
|
||||
<p id="consent-display-name" class="oc-light oc-consent-headline"></p>
|
||||
<p id="consent-username" class="oc-light oc-consent-username"></p>
|
||||
@@ -127,13 +127,16 @@
|
||||
if (!desc) desc = "Scope: " + scope;
|
||||
var li = document.createElement("li");
|
||||
li.className = "oc-consent-scope-item";
|
||||
var scopeId = "consent-scope-" + alias;
|
||||
var cb = document.createElement("input");
|
||||
cb.type = "checkbox";
|
||||
cb.id = scopeId;
|
||||
cb.checked = true;
|
||||
cb.disabled = true;
|
||||
cb.className = "oc-consent-checkbox";
|
||||
var label = document.createElement("span");
|
||||
var label = document.createElement("label");
|
||||
label.className = "oc-light";
|
||||
label.setAttribute("for", scopeId);
|
||||
label.textContent = desc;
|
||||
li.appendChild(cb);
|
||||
li.appendChild(label);
|
||||
|
||||
@@ -14,8 +14,8 @@
|
||||
<img class="oc-logo" src="{{.LogoURL}}" alt="ownCloud">
|
||||
<h1 class="oc-invisible-sr">{{.Headline}}</h1>
|
||||
<p class="oc-message">{{.Message}}</p>
|
||||
<footer class="oc-footer-message">ownCloud - a safe home for all your data</footer>
|
||||
</div>
|
||||
</main>
|
||||
<footer class="oc-footer-message">ownCloud - a safe home for all your data</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -23,12 +23,12 @@
|
||||
data-msg-sign-in="{{.ButtonSignIn}}">
|
||||
<div>
|
||||
<label class="oc-label" for="oc-login-username">{{.LabelUsername}}</label>
|
||||
<input class="oc-input" type="text" id="oc-login-username" name="username" autocomplete="username" placeholder="{{.LabelUsername}}" required>
|
||||
<input class="oc-input" type="text" id="oc-login-username" name="username" autocomplete="username" placeholder="{{.LabelUsername}}" aria-describedby="oc-login-error-message" required>
|
||||
</div>
|
||||
<div>
|
||||
<label class="oc-label" for="oc-login-password">{{.LabelPassword}}</label>
|
||||
<input class="oc-input" type="password" id="oc-login-password" name="password" autocomplete="current-password" placeholder="{{.LabelPassword}}" required>
|
||||
<p id="oc-login-error-message" class="oc-error-message" hidden></p>
|
||||
<input class="oc-input" type="password" id="oc-login-password" name="password" autocomplete="current-password" placeholder="{{.LabelPassword}}" aria-describedby="oc-login-error-message" required>
|
||||
<p id="oc-login-error-message" class="oc-error-message" role="alert" aria-live="assertive" hidden></p>
|
||||
</div>
|
||||
<div>
|
||||
<button class="oc-button-primary" type="submit" id="submit-btn">{{.ButtonSignIn}}</button>
|
||||
@@ -103,12 +103,16 @@
|
||||
errorEl.hidden = false;
|
||||
usernameEl.classList.add("error");
|
||||
passwordEl.classList.add("error");
|
||||
usernameEl.setAttribute("aria-invalid", "true");
|
||||
passwordEl.setAttribute("aria-invalid", "true");
|
||||
}
|
||||
|
||||
function hideError() {
|
||||
errorEl.hidden = true;
|
||||
usernameEl.classList.remove("error");
|
||||
passwordEl.classList.remove("error");
|
||||
usernameEl.removeAttribute("aria-invalid");
|
||||
passwordEl.removeAttribute("aria-invalid");
|
||||
}
|
||||
|
||||
function setLoading(loading) {
|
||||
|
||||
@@ -297,10 +297,19 @@ main {
|
||||
}
|
||||
|
||||
.oc-input:focus {
|
||||
outline: none;
|
||||
outline: 2px solid #00b3f0;
|
||||
outline-offset: 1px;
|
||||
border: 1px solid #fff;
|
||||
}
|
||||
|
||||
.oc-chooseaccount-item:focus-visible,
|
||||
.oc-button-primary:focus-visible,
|
||||
.oc-button-cancel:focus-visible,
|
||||
.oc-button-consent:focus-visible {
|
||||
outline: 2px solid #00b3f0;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.oc-button-primary {
|
||||
display: block;
|
||||
width: 100%;
|
||||
|
||||
@@ -14,8 +14,8 @@
|
||||
<img class="oc-logo" src="{{.LogoURL}}" alt="ownCloud">
|
||||
<h1 class="oc-invisible-sr">{{.Headline}}</h1>
|
||||
<p class="oc-message">{{.Message}}</p>
|
||||
<footer class="oc-footer-message">ownCloud - a safe home for all your data</footer>
|
||||
</div>
|
||||
</main>
|
||||
<footer class="oc-footer-message">ownCloud - a safe home for all your data</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -91,8 +91,9 @@ func OCMConfigFromStruct(cfg *config.Config, logger log.Logger) map[string]inter
|
||||
"service_account_secret": cfg.ServiceAccount.Secret,
|
||||
},
|
||||
"dataprovider": map[string]interface{}{
|
||||
"prefix": "data",
|
||||
"driver": "ocmreceived",
|
||||
"prefix": "data",
|
||||
"driver": "ocmreceived",
|
||||
"upload_directory": cfg.OCMStorageProvider.StorageRoot,
|
||||
"drivers": map[string]interface{}{
|
||||
"ocmreceived": map[string]interface{}{
|
||||
"insecure": cfg.OCMStorageProvider.Insecure,
|
||||
@@ -157,9 +158,9 @@ func OCMConfigFromStruct(cfg *config.Config, logger log.Logger) map[string]inter
|
||||
"file": cfg.OCMShareProvider.Drivers.JSON.File,
|
||||
},
|
||||
},
|
||||
"gatewaysvc": cfg.Reva.Address,
|
||||
"provider_domain": providerDomain,
|
||||
"webdav_endpoint": cfg.Commons.OcisURL,
|
||||
"gatewaysvc": cfg.Reva.Address,
|
||||
"provider_domain": providerDomain,
|
||||
"webdav_endpoint": cfg.Commons.OcisURL,
|
||||
"webapp_template": cfg.OCMShareProvider.WebappTemplate,
|
||||
"client_insecure": cfg.OCMShareProvider.Insecure,
|
||||
"enable_user_sharing": cfg.OCMShareProvider.EnableUserSharing,
|
||||
@@ -181,11 +182,14 @@ func OCMConfigFromStruct(cfg *config.Config, logger log.Logger) map[string]inter
|
||||
},
|
||||
},
|
||||
"storageprovider": map[string]interface{}{
|
||||
"driver": "ocmreceived",
|
||||
"driver": "ocmreceived",
|
||||
"upload_directory": cfg.OCMStorageProvider.StorageRoot,
|
||||
"drivers": map[string]interface{}{
|
||||
"ocmreceived": map[string]interface{}{
|
||||
"insecure": cfg.OCMStorageProvider.Insecure,
|
||||
"storage_root": cfg.OCMStorageProvider.StorageRoot,
|
||||
"insecure": cfg.OCMStorageProvider.Insecure,
|
||||
"storage_root": cfg.OCMStorageProvider.StorageRoot,
|
||||
"service_account_id": cfg.ServiceAccount.ID,
|
||||
"service_account_secret": cfg.ServiceAccount.Secret,
|
||||
},
|
||||
},
|
||||
"data_server_url": cfg.OCMStorageProvider.DataServerURL,
|
||||
|
||||
@@ -379,8 +379,8 @@
|
||||
"swatch-passive-hover-outline": "#F7D496",
|
||||
"swatch-passive-muted": "#99bae0",
|
||||
"swatch-passive-contrast": "#000000",
|
||||
"swatch-primary-default": "#F0AA39",
|
||||
"swatch-primary-hover": "#CA912B",
|
||||
"swatch-primary-default": "#9C6B00",
|
||||
"swatch-primary-hover": "#6C4500",
|
||||
"swatch-primary-muted": "#F0AA39",
|
||||
"swatch-primary-muted-hover": "#CA912B",
|
||||
"swatch-primary-gradient": "#F0AA39",
|
||||
@@ -500,8 +500,8 @@
|
||||
"input-bg": "#000000",
|
||||
"input-border": "#ffffff",
|
||||
"input-text-default": "#ffffff",
|
||||
"input-text-muted": "#f8f8f8",
|
||||
"search-input-text-muted": "#f8f8f8",
|
||||
"input-text-muted": "#bdbfc3",
|
||||
"search-input-text-muted": "#bdbfc3",
|
||||
"swatch-brand-default": "#191A25",
|
||||
"swatch-brand-hover": "#ffffff",
|
||||
"swatch-brand-contrast": "#F0AA39",
|
||||
|
||||
Vendored
BIN
Binary file not shown.
@@ -384,6 +384,7 @@ class SpacesContext implements Context {
|
||||
* @param string $spaceName
|
||||
* @param string $fileName
|
||||
* @param bool $federatedShare
|
||||
* @param bool $isVault
|
||||
*
|
||||
* @return ResponseInterface
|
||||
* @throws GuzzleException
|
||||
@@ -393,6 +394,7 @@ class SpacesContext implements Context {
|
||||
string $spaceName,
|
||||
string $fileName,
|
||||
bool $federatedShare = false,
|
||||
bool $isVault = false,
|
||||
): ResponseInterface {
|
||||
$baseUrl = $this->featureContext->getBaseUrl();
|
||||
|
||||
@@ -400,18 +402,27 @@ class SpacesContext implements Context {
|
||||
$remoteItemId = $this->getSharesRemoteItemId($user, $spaceName);
|
||||
$spaceId = \rawurlencode($remoteItemId);
|
||||
} else {
|
||||
$space = $this->getSpaceByName($user, $spaceName);
|
||||
$space = $this->getSpaceByName($user, $spaceName, $isVault);
|
||||
$spaceId = $space["id"];
|
||||
}
|
||||
|
||||
$davPath = WebdavHelper::getDavPath(WebDavHelper::DAV_VERSION_SPACES, $spaceId);
|
||||
$fullUrl = "$baseUrl/$davPath/$fileName";
|
||||
|
||||
$headers = [];
|
||||
if (KeycloakHelper::isTestingWithKeycloak()) {
|
||||
$accessToken = $this->featureContext->getOcisUserToken($user)['token']['accessToken'];
|
||||
$headers['Authorization'] = 'Bearer ' . $accessToken;
|
||||
$user = null;
|
||||
$password = null;
|
||||
} else {
|
||||
$password = $this->featureContext->getPasswordForUser($user);
|
||||
}
|
||||
return HttpRequestHelper::get(
|
||||
$fullUrl,
|
||||
$user,
|
||||
$this->featureContext->getPasswordForUser($user),
|
||||
[],
|
||||
$password,
|
||||
$headers,
|
||||
"{}",
|
||||
);
|
||||
}
|
||||
@@ -951,11 +962,12 @@ class SpacesContext implements Context {
|
||||
}
|
||||
|
||||
/**
|
||||
* @Then /^for user "([^"]*)" folder "([^"]*)" of the space "([^"]*)" should (not|)\s?contain these (?:files|entries):$/
|
||||
* @Then /^for user "([^"]*)" folder "([^"]*)" of the space "([^"]*)"(| in vault)? should (not|)\s?contain these (?:files|entries):$/
|
||||
*
|
||||
* @param string $user
|
||||
* @param string $folderPath
|
||||
* @param string $spaceName
|
||||
* @param string $isVault
|
||||
* @param string $shouldOrNot (not|)
|
||||
* @param TableNode $expectedFiles
|
||||
*
|
||||
@@ -967,11 +979,13 @@ class SpacesContext implements Context {
|
||||
string $user,
|
||||
string $folderPath,
|
||||
string $spaceName,
|
||||
string $isVault,
|
||||
string $shouldOrNot,
|
||||
TableNode $expectedFiles,
|
||||
): void {
|
||||
$space = $this->getSpaceByName($user, $spaceName);
|
||||
$this->featureContext->setResponse($this->propfindSpace($user, $spaceName, $folderPath));
|
||||
$isVault = trim($isVault) === 'in vault';
|
||||
$space = $this->getSpaceByName($user, $spaceName, $isVault);
|
||||
$this->featureContext->setResponse($this->propfindSpace($user, $spaceName, $folderPath, $isVault));
|
||||
$this->featureContext->propfindResultShouldContainEntries(
|
||||
$shouldOrNot,
|
||||
$expectedFiles,
|
||||
@@ -983,11 +997,12 @@ class SpacesContext implements Context {
|
||||
}
|
||||
|
||||
/**
|
||||
* @Then /^for user "([^"]*)" the content of the file "([^"]*)" of the space "([^"]*)" should be "([^"]*)"$/
|
||||
* @Then /^for user "([^"]*)" the content of the file "([^"]*)" of the space "([^"]*)"(| in vault) should be "([^"]*)"$/
|
||||
*
|
||||
* @param string $user
|
||||
* @param string $file
|
||||
* @param string $spaceName
|
||||
* @param string $isVault
|
||||
* @param string $fileContent
|
||||
*
|
||||
* @return void
|
||||
@@ -998,9 +1013,11 @@ class SpacesContext implements Context {
|
||||
string $user,
|
||||
string $file,
|
||||
string $spaceName,
|
||||
string $isVault,
|
||||
string $fileContent,
|
||||
): void {
|
||||
$actualFileContent = $this->getFileData($user, $spaceName, $file)->getBody()->getContents();
|
||||
$isVault = trim($isVault) === 'in vault';
|
||||
$actualFileContent = $this->getFileData($user, $spaceName, $file, false, $isVault)->getBody()->getContents();
|
||||
Assert::assertEquals($fileContent, $actualFileContent, "$file does not contain $fileContent");
|
||||
}
|
||||
|
||||
@@ -2080,15 +2097,15 @@ class SpacesContext implements Context {
|
||||
}
|
||||
|
||||
/**
|
||||
* @When /^user "([^"]*)" copies (?:file|folder) "([^"]*)" from space "([^"]*)" to "([^"]*)" inside space "([^"]*)" using the WebDAV API$/
|
||||
* @When /^user "([^"]*)" copies (?:file|folder) "([^"]*)" from space "([^"]*)" to "([^"]*)" inside space "([^"]*)"(?: with following headers) using the WebDAV API$/
|
||||
* @When /^user "([^"]*)" copies (?:file|folder) "([^"]*)" from space "([^"]*)"(| in vault)? to "([^"]*)" inside space "([^"]*)"(| in vault)? using the WebDAV API$/
|
||||
*
|
||||
* @param string $user
|
||||
* @param string $fileSource
|
||||
* @param string $fromSpaceName
|
||||
* @param string $isSourceVault
|
||||
* @param string $fileDestination
|
||||
* @param string $toSpaceName
|
||||
* @param TableNode|null $table
|
||||
* @param string $isDestinationVault
|
||||
*
|
||||
* @return void
|
||||
* @throws GuzzleException
|
||||
@@ -2097,15 +2114,86 @@ class SpacesContext implements Context {
|
||||
string $user,
|
||||
string $fileSource,
|
||||
string $fromSpaceName,
|
||||
string $isSourceVault,
|
||||
string $fileDestination,
|
||||
string $toSpaceName,
|
||||
string $isDestinationVault,
|
||||
): void {
|
||||
$isSourceVault = trim($isSourceVault) === "in vault";
|
||||
$isDestinationVault = trim($isDestinationVault) === "in vault";
|
||||
$this->copyFileBetweenSpaces(
|
||||
$user,
|
||||
$fileSource,
|
||||
$fromSpaceName,
|
||||
$fileDestination,
|
||||
$toSpaceName,
|
||||
$isSourceVault,
|
||||
$isDestinationVault,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @When /^user "([^"]*)" copies (?:file|folder) "([^"]*)" from space "([^"]*)" to "([^"]*)" inside space "([^"]*)" with following headers using the WebDAV API$/
|
||||
*
|
||||
* @param string $user
|
||||
* @param string $fileSource
|
||||
* @param string $fromSpaceName
|
||||
* @param string $fileDestination
|
||||
* @param string $toSpaceName
|
||||
* @param TableNode $table
|
||||
*
|
||||
* @return void
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
public function userCopiesFileFromAndToSpaceBetweenSpacesWithHeaders(
|
||||
string $user,
|
||||
string $fileSource,
|
||||
string $fromSpaceName,
|
||||
string $fileDestination,
|
||||
string $toSpaceName,
|
||||
TableNode $table,
|
||||
): void {
|
||||
$this->copyFileBetweenSpaces(
|
||||
$user,
|
||||
$fileSource,
|
||||
$fromSpaceName,
|
||||
$fileDestination,
|
||||
$toSpaceName,
|
||||
false,
|
||||
false,
|
||||
$table,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $user
|
||||
* @param string $fileSource
|
||||
* @param string $fromSpaceName
|
||||
* @param string $fileDestination
|
||||
* @param string $toSpaceName
|
||||
* @param boolean $isSourceVault
|
||||
* @param boolean $isDestinationVault
|
||||
* @param TableNode|null $table
|
||||
*
|
||||
* @return void
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
private function copyFileBetweenSpaces(
|
||||
string $user,
|
||||
string $fileSource,
|
||||
string $fromSpaceName,
|
||||
string $fileDestination,
|
||||
string $toSpaceName,
|
||||
?bool $isSourceVault = false,
|
||||
?bool $isDestinationVault = false,
|
||||
?TableNode $table = null,
|
||||
): void {
|
||||
$space = $this->getSpaceByName($user, $fromSpaceName);
|
||||
$space = $this->getSpaceByName($user, $fromSpaceName, $isSourceVault);
|
||||
$headers['Destination'] = $this->destinationHeaderValueWithSpaceName(
|
||||
$user,
|
||||
$fileDestination,
|
||||
$toSpaceName,
|
||||
$isDestinationVault,
|
||||
);
|
||||
|
||||
if ($table !== null) {
|
||||
@@ -2281,6 +2369,7 @@ class SpacesContext implements Context {
|
||||
* @param string $user
|
||||
* @param string $fileDestination
|
||||
* @param string $spaceName
|
||||
* @param boolean $isVault
|
||||
* @param string|null $endPath
|
||||
*
|
||||
* @return string
|
||||
@@ -2290,9 +2379,10 @@ class SpacesContext implements Context {
|
||||
string $user,
|
||||
string $fileDestination,
|
||||
string $spaceName,
|
||||
bool $isVault = false,
|
||||
?string $endPath = null,
|
||||
): string {
|
||||
$space = $this->getSpaceByName($user, $spaceName);
|
||||
$space = $this->getSpaceByName($user, $spaceName, $isVault);
|
||||
$fileDestination = $this->escapePath(\ltrim($fileDestination, "/"));
|
||||
$baseUrl = $this->featureContext->getBaseUrl();
|
||||
$davPath = WebdavHelper::getDavPath(WebDavHelper::DAV_VERSION_SPACES, $space["id"]);
|
||||
@@ -2310,11 +2400,19 @@ class SpacesContext implements Context {
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
public function copyFilesAndFoldersRequest(string $user, string $fullUrl, array $headers): ResponseInterface {
|
||||
if (KeycloakHelper::isTestingWithKeycloak()) {
|
||||
$access_token = $this->featureContext->getOcisUserToken($user)["token"]["accessToken"];
|
||||
$headers['Authorization'] = 'Bearer ' . $access_token;
|
||||
$user = null;
|
||||
$password = null;
|
||||
} else {
|
||||
$password = $this->featureContext->getPasswordForUser($user);
|
||||
}
|
||||
return HttpRequestHelper::sendRequest(
|
||||
$fullUrl,
|
||||
'COPY',
|
||||
$user,
|
||||
$this->featureContext->getPasswordForUser($user),
|
||||
$password,
|
||||
$headers,
|
||||
);
|
||||
}
|
||||
@@ -2354,6 +2452,7 @@ class SpacesContext implements Context {
|
||||
$user,
|
||||
$fileDestination,
|
||||
$toSpaceName,
|
||||
false,
|
||||
$fileId,
|
||||
);
|
||||
}
|
||||
@@ -2401,6 +2500,7 @@ class SpacesContext implements Context {
|
||||
$user,
|
||||
$fileDestination,
|
||||
$spaceName,
|
||||
false,
|
||||
$fileId,
|
||||
);
|
||||
}
|
||||
@@ -2445,6 +2545,7 @@ class SpacesContext implements Context {
|
||||
$user,
|
||||
$fileDestination,
|
||||
$spaceName,
|
||||
false,
|
||||
$fileId,
|
||||
);
|
||||
}
|
||||
@@ -2493,6 +2594,7 @@ class SpacesContext implements Context {
|
||||
$user,
|
||||
$fileDestination,
|
||||
$spaceName,
|
||||
false,
|
||||
$fileId,
|
||||
);
|
||||
}
|
||||
@@ -2548,12 +2650,13 @@ class SpacesContext implements Context {
|
||||
}
|
||||
|
||||
/**
|
||||
* @Given /^user "([^"]*)" has uploaded a file inside space "([^"]*)" with content "([^"]*)" to "([^"]*)"$/
|
||||
* @Given /^user "([^"]*)" has uploaded a file inside space "([^"]*)" with content "([^"]*)" to "([^"]*)"(| in vault)?$/
|
||||
*
|
||||
* @param string $user
|
||||
* @param string $spaceName
|
||||
* @param string $fileContent
|
||||
* @param string $destination
|
||||
* @param string $isVault
|
||||
*
|
||||
* @return array
|
||||
* @throws GuzzleException
|
||||
@@ -2563,8 +2666,10 @@ class SpacesContext implements Context {
|
||||
string $spaceName,
|
||||
string $fileContent,
|
||||
string $destination,
|
||||
string $isVault,
|
||||
): array {
|
||||
$space = $this->getSpaceByName($user, $spaceName);
|
||||
$isVault = trim($isVault) === "in vault";
|
||||
$space = $this->getSpaceByName($user, $spaceName, $isVault);
|
||||
$response = $this->featureContext->uploadFileWithContent(
|
||||
$user,
|
||||
$fileContent,
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
services:
|
||||
acceptance-tests:
|
||||
image: owncloudci/php:8.2
|
||||
image: owncloudci/php:8.4
|
||||
working_dir: /ocis
|
||||
command: /bin/bash /test/run-tests.sh
|
||||
command: >
|
||||
/bin/bash -c "command -v composer >/dev/null 2>&1 ||
|
||||
(php -r \"copy('https://getcomposer.org/installer', '/tmp/composer-setup.php');\" &&
|
||||
php /tmp/composer-setup.php --install-dir=/usr/local/bin --filename=composer);
|
||||
/bin/bash /test/run-tests.sh"
|
||||
environment:
|
||||
OCIS_ROOT: /ocis
|
||||
TEST_SERVER_URL: https://ocis-server:9200
|
||||
|
||||
@@ -182,3 +182,94 @@ Feature: vault
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
Scenario: user copies folder from drive to vault
|
||||
Given user "Alice" has logged in via web UI
|
||||
And user "Alice" has created a folder "driveFolder" in space "Personal"
|
||||
When user "Alice" copies folder "driveFolder" from space "Personal" to "driveFolder" inside space "Personal" in vault using the WebDAV API
|
||||
Then the HTTP status code should be "201"
|
||||
And for user "Alice" the space "Personal" in vault should contain these entries:
|
||||
| driveFolder |
|
||||
And for user "Alice" the space "Personal" should contain these entries:
|
||||
| driveFolder |
|
||||
|
||||
|
||||
Scenario: user copies file from drive to vault
|
||||
Given user "Alice" has logged in via web UI
|
||||
And user "Alice" has uploaded a file inside space "Personal" with content "some content" to "testfile.txt"
|
||||
When user "Alice" copies file "testfile.txt" from space "Personal" to "testfile.txt" inside space "Personal" in vault using the WebDAV API
|
||||
Then the HTTP status code should be "201"
|
||||
And for user "Alice" the content of the file "testfile.txt" of the space "Personal" in vault should be "some content"
|
||||
And for user "Alice" the space "Personal" should contain these entries:
|
||||
| testfile.txt |
|
||||
|
||||
|
||||
Scenario: user tries to copy folder from vault to drive
|
||||
Given user "Alice" has logged in via web UI
|
||||
And user "Alice" has created a folder "vaultFolder" in space "Personal" in vault
|
||||
When user "Alice" copies folder "vaultFolder" from space "Personal" in vault to "vaultFolder" inside space "Personal" using the WebDAV API
|
||||
Then the HTTP status code should be "409"
|
||||
And for user "Alice" the space "Personal" should not contain these entries:
|
||||
| vaultFolder |
|
||||
And for user "Alice" the space "Personal" in vault should contain these entries:
|
||||
| vaultFolder |
|
||||
|
||||
|
||||
Scenario: user tries to copy file from vault to drive
|
||||
Given user "Alice" has logged in via web UI
|
||||
And user "Alice" has uploaded a file inside space "Personal" with content "some content" to "testfile.txt" in vault
|
||||
When user "Alice" copies file "testfile.txt" from space "Personal" in vault to "testfile.txt" inside space "Personal" using the WebDAV API
|
||||
Then the HTTP status code should be "409"
|
||||
And for user "Alice" the space "Personal" should not contain these entries:
|
||||
| testfile.txt |
|
||||
And for user "Alice" the space "Personal" in vault should contain these entries:
|
||||
| testfile.txt |
|
||||
|
||||
|
||||
Scenario: user copies sub-folder from drive to vault
|
||||
Given user "Alice" has logged in via web UI
|
||||
And user "Alice" has created a folder "driveFolder" in space "Personal"
|
||||
And user "Alice" has created a folder "driveFolder/subFolder" in space "Personal"
|
||||
When user "Alice" copies folder "driveFolder/subFolder" from space "Personal" to "subFolder" inside space "Personal" in vault using the WebDAV API
|
||||
Then the HTTP status code should be "201"
|
||||
And for user "Alice" the space "Personal" in vault should contain these entries:
|
||||
| subFolder |
|
||||
And for user "Alice" folder "driveFolder" of the space "Personal" should contain these entries:
|
||||
| subFolder |
|
||||
|
||||
|
||||
Scenario: user copies file inside folder from drive to vault
|
||||
Given user "Alice" has logged in via web UI
|
||||
And user "Alice" has created a folder "driveFolder" in space "Personal"
|
||||
And user "Alice" has uploaded a file inside space "Personal" with content "some content" to "driveFolder/testfile.txt"
|
||||
When user "Alice" copies file "driveFolder/testfile.txt" from space "Personal" to "testfile.txt" inside space "Personal" in vault using the WebDAV API
|
||||
Then the HTTP status code should be "201"
|
||||
And for user "Alice" the content of the file "testfile.txt" of the space "Personal" in vault should be "some content"
|
||||
And for user "Alice" folder "driveFolder" of the space "Personal" should contain these entries:
|
||||
| testfile.txt |
|
||||
|
||||
|
||||
Scenario: user copies sub-folder from drive to a folder in vault
|
||||
Given user "Alice" has logged in via web UI
|
||||
And user "Alice" has created a folder "driveFolder" in space "Personal"
|
||||
And user "Alice" has created a folder "driveFolder/subFolder" in space "Personal"
|
||||
And user "Alice" has created a folder "vaultFolder" in space "Personal" in vault
|
||||
When user "Alice" copies folder "driveFolder/subFolder" from space "Personal" to "vaultFolder/subFolder" inside space "Personal" in vault using the WebDAV API
|
||||
Then the HTTP status code should be "201"
|
||||
And for user "Alice" folder "vaultFolder" of the space "Personal" in vault should contain these entries:
|
||||
| subFolder |
|
||||
And for user "Alice" folder "driveFolder" of the space "Personal" should contain these entries:
|
||||
| subFolder |
|
||||
|
||||
|
||||
Scenario: user copies file inside folder from drive to a folder in vault
|
||||
Given user "Alice" has logged in via web UI
|
||||
And user "Alice" has created a folder "driveFolder" in space "Personal"
|
||||
And user "Alice" has uploaded a file inside space "Personal" with content "some content" to "driveFolder/testfile.txt"
|
||||
And user "Alice" has created a folder "vaultFolder" in space "Personal" in vault
|
||||
When user "Alice" copies file "driveFolder/testfile.txt" from space "Personal" to "vaultFolder/testfile.txt" inside space "Personal" in vault using the WebDAV API
|
||||
Then the HTTP status code should be "201"
|
||||
And for user "Alice" the content of the file "vaultFolder/testfile.txt" of the space "Personal" in vault should be "some content"
|
||||
And for user "Alice" folder "driveFolder" of the space "Personal" should contain these entries:
|
||||
| testfile.txt |
|
||||
@@ -0,0 +1 @@
|
||||
lorem
|
||||
@@ -0,0 +1 @@
|
||||
lorem
|
||||
@@ -0,0 +1 @@
|
||||
lorem
|
||||
@@ -0,0 +1 @@
|
||||
lorem
|
||||
+24
@@ -1,3 +1,27 @@
|
||||
Release 1.7.0
|
||||
=============
|
||||
|
||||
**Changes**
|
||||
|
||||
**Breaking changes**
|
||||
|
||||
* To address a security issue, it was necessary to add a `MaxDepth` option to
|
||||
`ReadSettings` to limit the depth of XML trees during parsing. A generous
|
||||
default value of 1024 was chosen to avoid breaking most existing code.
|
||||
However, if your code is processing XML hierarchies with a depth greater
|
||||
than 1024, you will need to assign your `Document` a `ReadSettings` that has
|
||||
a `MaxDepth` set to a higher value.
|
||||
|
||||
**Security Fixes**
|
||||
|
||||
* Limited the depth of XML trees processed by all `ReadFrom` functions during
|
||||
parsing.
|
||||
* Fixed a `CompilePath` index-out-of-range panic that could be caused by a
|
||||
missing path filter key.
|
||||
* Sanitized the contents of XML text, comment, ProcInst and Directive tokens
|
||||
provided by the user.
|
||||
|
||||
|
||||
Release 1.6.0
|
||||
=============
|
||||
|
||||
|
||||
+31
-17
@@ -13,6 +13,7 @@ import (
|
||||
"errors"
|
||||
"io"
|
||||
"iter"
|
||||
"maps"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
@@ -27,6 +28,10 @@ const (
|
||||
// ErrXML is returned when XML parsing fails due to incorrect formatting.
|
||||
var ErrXML = errors.New("etree: invalid XML format")
|
||||
|
||||
// ErrMaxDepth is returned when the depth of the XML tree being read exceeds
|
||||
// the maximum depth allowed by ReadSettings.MaxDepth.
|
||||
var ErrMaxDepth = errors.New("etree: XML tree exceeds maximum depth")
|
||||
|
||||
// cdataPrefix is used to detect CDATA text when ReadSettings.PreserveCData is
|
||||
// true.
|
||||
var cdataPrefix = []byte("<![CDATA[")
|
||||
@@ -76,8 +81,18 @@ type ReadSettings struct {
|
||||
// whether an end element is present. Commonly set to xml.HTMLAutoClose.
|
||||
// Default: nil.
|
||||
AutoClose []string
|
||||
|
||||
// MaxDepth is the maximum depth of the XML tree to parse. If the depth of
|
||||
// the XML tree exceeds this value, all ReadFrom* functions return the
|
||||
// error ErrMaxDepth. If MaxDepth is zero or negative, a depth limit of
|
||||
// 1024 is used. Default: 0 (i.e., a limit of 1024).
|
||||
MaxDepth int
|
||||
}
|
||||
|
||||
// defaultMaxDepth is the maximum depth of an XML tree parsed by ReadFrom*
|
||||
// functions when ReadSettings.MaxDepth is not set to a positive value.
|
||||
const defaultMaxDepth = 1024
|
||||
|
||||
// defaultCharsetReader is used by the xml decoder when the ReadSettings
|
||||
// CharsetReader value is nil. It behaves as a "pass-through", ignoring
|
||||
// the requested charset parameter and skipping conversion altogether.
|
||||
@@ -87,18 +102,9 @@ func defaultCharsetReader(charset string, input io.Reader) (io.Reader, error) {
|
||||
|
||||
// dup creates a duplicate of the ReadSettings object.
|
||||
func (s *ReadSettings) dup() ReadSettings {
|
||||
var entityCopy map[string]string
|
||||
if s.Entity != nil {
|
||||
entityCopy = make(map[string]string)
|
||||
for k, v := range s.Entity {
|
||||
entityCopy[k] = v
|
||||
}
|
||||
}
|
||||
return ReadSettings{
|
||||
CharsetReader: s.CharsetReader,
|
||||
Permissive: s.Permissive,
|
||||
Entity: entityCopy,
|
||||
}
|
||||
c := *s
|
||||
c.Entity = maps.Clone(s.Entity)
|
||||
return c
|
||||
}
|
||||
|
||||
// WriteSettings determine the behavior of the Document's WriteTo* functions.
|
||||
@@ -913,6 +919,11 @@ func (e *Element) readFrom(ri io.Reader, settings ReadSettings) (n int64, err er
|
||||
attrCheck := make(map[xml.Name]int)
|
||||
dec := newDecoder(r, settings)
|
||||
|
||||
maxDepth := settings.MaxDepth
|
||||
if maxDepth <= 0 {
|
||||
maxDepth = defaultMaxDepth
|
||||
}
|
||||
|
||||
var stack stack[*Element]
|
||||
stack.push(e)
|
||||
for {
|
||||
@@ -942,6 +953,9 @@ func (e *Element) readFrom(ri io.Reader, settings ReadSettings) (n int64, err er
|
||||
|
||||
switch t := t.(type) {
|
||||
case xml.StartElement:
|
||||
if len(stack.data) > maxDepth {
|
||||
return r.Bytes(), ErrMaxDepth
|
||||
}
|
||||
e := newElement(t.Name.Space, t.Name.Local, top)
|
||||
if settings.PreserveDuplicateAttrs || len(t.Attr) < 2 {
|
||||
for _, a := range t.Attr {
|
||||
@@ -1622,7 +1636,7 @@ func (c *CharData) Index() int {
|
||||
func (c *CharData) WriteTo(w Writer, s *WriteSettings) {
|
||||
if c.IsCData() {
|
||||
w.WriteString(`<![CDATA[`)
|
||||
w.WriteString(c.Data)
|
||||
sanitizeCData(w, c.Data)
|
||||
w.WriteString(`]]>`)
|
||||
} else {
|
||||
var m escapeMode
|
||||
@@ -1704,7 +1718,7 @@ func (c *Comment) Index() int {
|
||||
// WriteTo serialies the comment to the writer.
|
||||
func (c *Comment) WriteTo(w Writer, s *WriteSettings) {
|
||||
w.WriteString("<!--")
|
||||
w.WriteString(c.Data)
|
||||
sanitizeComment(w, c.Data)
|
||||
w.WriteString("-->")
|
||||
}
|
||||
|
||||
@@ -1769,7 +1783,7 @@ func (d *Directive) Index() int {
|
||||
// WriteTo serializes the XML directive to the writer.
|
||||
func (d *Directive) WriteTo(w Writer, s *WriteSettings) {
|
||||
w.WriteString("<!")
|
||||
w.WriteString(d.Data)
|
||||
sanitizeDirective(w, d.Data)
|
||||
w.WriteString(">")
|
||||
}
|
||||
|
||||
@@ -1837,10 +1851,10 @@ func (p *ProcInst) Index() int {
|
||||
// WriteTo serializes the processing instruction to the writer.
|
||||
func (p *ProcInst) WriteTo(w Writer, s *WriteSettings) {
|
||||
w.WriteString("<?")
|
||||
w.WriteString(p.Target)
|
||||
sanitizeProcInst(w, p.Target)
|
||||
if p.Inst != "" {
|
||||
w.WriteByte(' ')
|
||||
w.WriteString(p.Inst)
|
||||
sanitizeProcInst(w, p.Inst)
|
||||
}
|
||||
w.WriteString("?>")
|
||||
}
|
||||
|
||||
+114
@@ -384,6 +384,120 @@ func escapeString(w Writer, s string, m escapeMode) {
|
||||
w.WriteString(s[last:])
|
||||
}
|
||||
|
||||
// sanitizeCData writes the sanitized contents of a CDATA section to the
|
||||
// writer. XML provides no way to escape the "]]>" sequence within a CDATA
|
||||
// section, so any occurrence of it is split across two CDATA sections.
|
||||
func sanitizeCData(w Writer, s string) {
|
||||
for {
|
||||
i := strings.Index(s, "]]>")
|
||||
if i < 0 {
|
||||
break
|
||||
}
|
||||
w.WriteString(s[:i+2])
|
||||
w.WriteString("]]><![CDATA[")
|
||||
s = s[i+2:]
|
||||
}
|
||||
w.WriteString(s)
|
||||
}
|
||||
|
||||
// sanitizeComment writes the sanitized contents of a comment to the writer.
|
||||
// An XML comment may not contain the string "--", and it may not end with a
|
||||
// '-'. Because XML provides no way to escape these sequences, spaces are
|
||||
// inserted where necessary.
|
||||
func sanitizeComment(w Writer, s string) {
|
||||
last, hyphen := 0, false
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] != '-' {
|
||||
hyphen = false
|
||||
continue
|
||||
}
|
||||
if hyphen {
|
||||
w.WriteString(s[last:i])
|
||||
w.WriteByte(' ')
|
||||
last = i
|
||||
}
|
||||
hyphen = true
|
||||
}
|
||||
w.WriteString(s[last:])
|
||||
if hyphen {
|
||||
w.WriteByte(' ')
|
||||
}
|
||||
}
|
||||
|
||||
// sanitizeProcInst writes the contents of a sanitized processing instruction
|
||||
// to the writer. XML provides no way to escape the "?>" sequence within a
|
||||
// processing instruction, so a space is inserted between the two characters.
|
||||
func sanitizeProcInst(w Writer, s string) {
|
||||
for {
|
||||
i := strings.Index(s, "?>")
|
||||
if i < 0 {
|
||||
break
|
||||
}
|
||||
w.WriteString(s[:i+1])
|
||||
w.WriteByte(' ')
|
||||
s = s[i+1:]
|
||||
}
|
||||
w.WriteString(s)
|
||||
}
|
||||
|
||||
// sanitizeDirective writes the sanitized contents of an XML directive to the
|
||||
// writer.
|
||||
func sanitizeDirective(w Writer, s string) {
|
||||
// The XML decoder reserves the character following "<!" for comments
|
||||
// ('-') and CDATA sections ('['), and it treats "<!>" as an unterminated
|
||||
// directive. Insert a space to avoid conflicts with reserved sequences.
|
||||
scan := s
|
||||
if s == "" || s[0] == '-' || s[0] == '[' {
|
||||
w.WriteByte(' ')
|
||||
} else {
|
||||
scan = s[1:]
|
||||
}
|
||||
|
||||
// A directive's contents may legitimately contain '<' and '>' characters,
|
||||
// so write them without modification when they are balanced.
|
||||
if isDirectiveBalanced(scan) {
|
||||
w.WriteString(s)
|
||||
return
|
||||
}
|
||||
|
||||
// The contents are unbalanced, so escape every character in the string.
|
||||
escapeString(w, s, escapeNormal)
|
||||
}
|
||||
|
||||
// isDirectiveBalanced returns true if the interpreted portion of an XML
|
||||
// directive's contents may be enclosed by "<!" and ">" without changing the
|
||||
// extents of the resulting directive.
|
||||
func isDirectiveBalanced(s string) bool {
|
||||
var quote byte
|
||||
var depth int
|
||||
for i := 0; i < len(s); i++ {
|
||||
switch c := s[i]; {
|
||||
case quote != 0:
|
||||
if c == quote {
|
||||
quote = 0
|
||||
}
|
||||
case c == '\'' || c == '"':
|
||||
quote = c
|
||||
case c == '>':
|
||||
if depth == 0 {
|
||||
return false
|
||||
}
|
||||
depth--
|
||||
case c == '<':
|
||||
if !strings.HasPrefix(s[i+1:], "!--") {
|
||||
depth++
|
||||
break
|
||||
}
|
||||
j := strings.Index(s[i+4:], "-->")
|
||||
if j < 0 {
|
||||
return false
|
||||
}
|
||||
i += 4 + j + 2
|
||||
}
|
||||
}
|
||||
return quote == 0 && depth == 0
|
||||
}
|
||||
|
||||
func isInCharacterRange(r rune) bool {
|
||||
return r == 0x09 ||
|
||||
r == 0x0A ||
|
||||
|
||||
+14
-2
@@ -281,7 +281,11 @@ func (c *compiler) parseSegment(path string) segment {
|
||||
c.err = ErrPath("path has invalid filter [brackets].")
|
||||
break
|
||||
}
|
||||
seg.filters = append(seg.filters, c.parseFilter(fpath[:len(fpath)-1]))
|
||||
filter := c.parseFilter(fpath[:len(fpath)-1])
|
||||
if c.err != ErrPath("") {
|
||||
break
|
||||
}
|
||||
seg.filters = append(seg.filters, filter)
|
||||
}
|
||||
return seg
|
||||
}
|
||||
@@ -320,7 +324,11 @@ func (c *compiler) parseFilter(path string) filter {
|
||||
// Filter contains [@attr='val'], [@attr="val"], [fn()='val'],
|
||||
// [fn()="val"], [tag='val'] or [tag="val"]?
|
||||
eqindex := strings.IndexByte(path, '=')
|
||||
if eqindex >= 0 && eqindex+1 < len(path) {
|
||||
if eqindex == 0 {
|
||||
c.err = ErrPath("path contains a filter expression with no key.")
|
||||
return nil
|
||||
}
|
||||
if eqindex > 0 && eqindex+1 < len(path) {
|
||||
quote := path[eqindex+1]
|
||||
if quote == '\'' || quote == '"' {
|
||||
rindex := nextIndex(path, quote, eqindex+2)
|
||||
@@ -334,6 +342,10 @@ func (c *compiler) parseFilter(path string) filter {
|
||||
|
||||
switch {
|
||||
case key[0] == '@':
|
||||
if len(key) == 1 {
|
||||
c.err = ErrPath("path contains a filter expression with no key.")
|
||||
return nil
|
||||
}
|
||||
return newFilterAttrVal(key[1:], value)
|
||||
case strings.HasSuffix(key, "()"):
|
||||
name := key[:len(key)-2]
|
||||
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
// Package oidc implements OpenID Connect client logic for the golang.org/x/oauth2 package.
|
||||
//
|
||||
// Construct a [Provider] and [oauth2.Config] through the identity provider's
|
||||
// discovery document with [NewProvider], and construct an ID Token verifier
|
||||
// with [Provider.Verifier]:
|
||||
//
|
||||
// provider, err := oidc.NewProvider(ctx, "https://accounts.google.com")
|
||||
// if err != nil {
|
||||
// // handle error
|
||||
// }
|
||||
//
|
||||
// // Configure an OpenID Connect aware OAuth2 client.
|
||||
// oauth2Config := oauth2.Config{
|
||||
// ClientID: clientID,
|
||||
// ClientSecret: clientSecret,
|
||||
// RedirectURL: redirectURL,
|
||||
// // Discovery returns the OAuth2 endpoints.
|
||||
// Endpoint: provider.Endpoint(),
|
||||
// // "openid" is a required scope for OpenID Connect flows.
|
||||
// Scopes: []string{oidc.ScopeOpenID, oidc.ScopeProfile, oidc.ScopeEmail},
|
||||
// }
|
||||
//
|
||||
// idTokenVerifier := provider.Verifier(&oidc.Config{ClientID: clientID})
|
||||
//
|
||||
// OAuth 2.0 redirects then opt into the OpenID Connect flow with [ScopeOpenID]:
|
||||
//
|
||||
// func handleRedirect(w http.ResponseWriter, r *http.Request) {
|
||||
// http.Redirect(w, r, oauth2Config.AuthCodeURL(state), http.StatusFound)
|
||||
// }
|
||||
//
|
||||
// When handling an OAuth 2.0 response, an [IDTokenVerifier] can be used to
|
||||
// validate the "id_token" payload, containing well-known fields such as the
|
||||
// user's email, name, and picture URL:
|
||||
//
|
||||
// func handleOAuth2Callback(w http.ResponseWriter, r *http.Request) {
|
||||
// // Verify state and other OAuth 2.0 responses.
|
||||
//
|
||||
// // Perform standard token exchange.
|
||||
// oauth2Token, err := oauth2Config.Exchange(r.Context(), r.URL.Query().Get("code"))
|
||||
// if err != nil {
|
||||
// // ...
|
||||
// }
|
||||
// // Extract the ID Token from OAuth2 token.
|
||||
// rawIDToken, ok := oauth2Token.Extra("id_token").(string)
|
||||
// if !ok {
|
||||
// // ...
|
||||
// }
|
||||
// // Parse and verify ID Token payload.
|
||||
// idToken, err := idTokenVerifier.Verify(r.Context(), rawIDToken)
|
||||
// if err != nil {
|
||||
// // ...
|
||||
// }
|
||||
// // Parse well-known claims from the token.
|
||||
// // https://openid.net/specs/openid-connect-core-1_0.html#Claims
|
||||
// var claims struct {
|
||||
// Email string `json:"email"`
|
||||
// EmailVerified bool `json:"email_verified"`
|
||||
// Name string `json:"name"`
|
||||
// Picture string `json:"picture"`
|
||||
// }
|
||||
// if err := idToken.Claims(&claims); err != nil {
|
||||
// // ...
|
||||
// }
|
||||
// }
|
||||
package oidc
|
||||
+8
@@ -30,3 +30,11 @@ var allAlgs = []jose.SignatureAlgorithm{
|
||||
jose.PS512,
|
||||
jose.EdDSA,
|
||||
}
|
||||
|
||||
var supportedJOSEAlgs = map[string]bool{}
|
||||
|
||||
func init() {
|
||||
for _, alg := range allAlgs {
|
||||
supportedJOSEAlgs[string(alg)] = true
|
||||
}
|
||||
}
|
||||
+58
-6
@@ -6,6 +6,7 @@ import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/ed25519"
|
||||
"crypto/rsa"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -17,8 +18,8 @@ import (
|
||||
|
||||
// StaticKeySet is a verifier that validates JWT against a static set of public keys.
|
||||
type StaticKeySet struct {
|
||||
// PublicKeys used to verify the JWT. Supported types are *rsa.PublicKey and
|
||||
// *ecdsa.PublicKey.
|
||||
// PublicKeys used to verify the JWT. Supported types are *rsa.PublicKey,
|
||||
// *ecdsa.PublicKey, and ed25519.PublicKey.
|
||||
PublicKeys []crypto.PublicKey
|
||||
}
|
||||
|
||||
@@ -53,8 +54,10 @@ func (s *StaticKeySet) VerifySignature(ctx context.Context, jwt string) ([]byte,
|
||||
// exposed for providers that don't support discovery or to prevent round trips to the
|
||||
// discovery URL.
|
||||
//
|
||||
// The returned KeySet is a long lived verifier that caches keys based on any
|
||||
// keys change. Reuse a common remote key set instead of creating new ones as needed.
|
||||
// The returned KeySet is a long lived verifier that caches keys in memory,
|
||||
// re-fetching from the remote URL when it encounters a key ID it hasn't seen.
|
||||
// Reuse a single remote key set rather than creating a new one for each
|
||||
// verification.
|
||||
func NewRemoteKeySet(ctx context.Context, jwksURL string) *RemoteKeySet {
|
||||
return newRemoteKeySet(ctx, jwksURL)
|
||||
}
|
||||
@@ -123,7 +126,7 @@ func (i *inflight) result() ([]jose.JSONWebKey, error) {
|
||||
return i.keys, i.err
|
||||
}
|
||||
|
||||
// paresdJWTKey is a context key that allows common setups to avoid parsing the
|
||||
// parsedJWTKey is a context key that allows common setups to avoid parsing the
|
||||
// JWT twice. It holds a *jose.JSONWebSignature value.
|
||||
var parsedJWTKey contextKey
|
||||
|
||||
@@ -233,6 +236,55 @@ func (r *RemoteKeySet) keysFromRemote(ctx context.Context) ([]jose.JSONWebKey, e
|
||||
}
|
||||
}
|
||||
|
||||
// jwkJSON implements custom logic for unmarshaling JSON Web Key Sets.
|
||||
type jwkJSON struct {
|
||||
Keys []jose.JSONWebKey
|
||||
}
|
||||
|
||||
func (j *jwkJSON) UnmarshalJSON(data []byte) error {
|
||||
var raw struct {
|
||||
Keys []json.RawMessage `json:"keys"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &raw); err != nil {
|
||||
return err
|
||||
}
|
||||
// For each key, attempt to determine if the algorithm is supported before
|
||||
// unmarshaling the key. This allows us to ignore keys with unsupported
|
||||
// algorithms, rather than failing to load the entire set.
|
||||
for _, key := range raw.Keys {
|
||||
var metadata struct {
|
||||
Alg string `json:"alg"`
|
||||
}
|
||||
if err := json.Unmarshal(key, &metadata); err != nil {
|
||||
return err
|
||||
}
|
||||
if metadata.Alg != "" {
|
||||
// Algorithms are technically optional, but if the key advertises an
|
||||
// algorithm we don't support, ignore it rather than failing to load
|
||||
// the entire key set.
|
||||
//
|
||||
// https://datatracker.ietf.org/doc/html/rfc7517#section-4.4
|
||||
//
|
||||
// This skip is currently implemented due to secp256k1, which some
|
||||
// providers use for signing with "ES256K". While we could also
|
||||
// ignore the curve, this seems like a more general check in case
|
||||
// providers start throwing in post-quantum algorithims or something
|
||||
// like that.
|
||||
//
|
||||
// https://github.com/coreos/go-oidc/issues/490
|
||||
if !supportedJOSEAlgs[metadata.Alg] {
|
||||
continue
|
||||
}
|
||||
}
|
||||
var jwk jose.JSONWebKey
|
||||
if err := json.Unmarshal(key, &jwk); err != nil {
|
||||
return err
|
||||
}
|
||||
j.Keys = append(j.Keys, jwk)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RemoteKeySet) updateKeys() ([]jose.JSONWebKey, error) {
|
||||
req, err := http.NewRequest("GET", r.jwksURL, nil)
|
||||
if err != nil {
|
||||
@@ -255,7 +307,7 @@ func (r *RemoteKeySet) updateKeys() ([]jose.JSONWebKey, error) {
|
||||
return nil, fmt.Errorf("oidc: get keys failed: %s %s", resp.Status, body)
|
||||
}
|
||||
|
||||
var keySet jose.JSONWebKeySet
|
||||
var keySet jwkJSON
|
||||
err = unmarshalResp(resp, body, &keySet)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("oidc: failed to decode keys: %v %s", err, body)
|
||||
|
||||
+4
-3
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -37,7 +38,7 @@ type LogoutToken struct {
|
||||
Expiry time.Time
|
||||
// Optional session ID claim ("sid").
|
||||
//
|
||||
// The exact semantics of session IDs very between identity providers. Use
|
||||
// The exact semantics of session IDs vary between identity providers. Use
|
||||
// your provider's documentation to determine what this correlates to and
|
||||
// how it should be handled.
|
||||
SessionID string
|
||||
@@ -98,7 +99,7 @@ type logoutTokenJSON struct {
|
||||
// }
|
||||
// verifier := provider.Verifier(oidcConfig)
|
||||
//
|
||||
// mux.HandleFunc("POST /logout", func(w http.ResponseWriter, r *http.Reequest) {
|
||||
// mux.HandleFunc("POST /logout", func(w http.ResponseWriter, r *http.Request) {
|
||||
// rawLogoutToken := r.PostFormValue("logout_token")
|
||||
// if rawLogoutToken == "" {
|
||||
// // ...
|
||||
@@ -163,7 +164,7 @@ func (v *IDTokenVerifier) VerifyLogout(ctx context.Context, rawLogoutToken strin
|
||||
|
||||
if !v.config.SkipClientIDCheck {
|
||||
if v.config.ClientID != "" {
|
||||
if !contains(t.Audience, v.config.ClientID) {
|
||||
if !slices.Contains(t.Audience, v.config.ClientID) {
|
||||
return nil, fmt.Errorf("oidc: expected logout token audience %q got %q", v.config.ClientID, t.Audience)
|
||||
}
|
||||
} else {
|
||||
|
||||
+115
-12
@@ -1,4 +1,3 @@
|
||||
// Package oidc implements OpenID Connect client logic for the golang.org/x/oauth2 package.
|
||||
package oidc
|
||||
|
||||
import (
|
||||
@@ -24,6 +23,26 @@ const (
|
||||
// ScopeOpenID is the mandatory scope for all OpenID Connect OAuth2 requests.
|
||||
ScopeOpenID = "openid"
|
||||
|
||||
// ScopeProfile can be used to request information about the user's profile,
|
||||
// such as "name", "picture", etc.
|
||||
//
|
||||
// The exact set of claims supported by identity providers differs widely,
|
||||
// though "name" and "picture" are commonly returned.
|
||||
//
|
||||
// See: https://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims
|
||||
ScopeProfile = "profile"
|
||||
|
||||
// ScopeEmail can be used to request the user's email address through the
|
||||
// "email" and "email_verified" claims.
|
||||
//
|
||||
// What it means to verify an email isn't well defined. Clients can
|
||||
// generally throw out emails when the "emvail_verified" claim is false, but
|
||||
// should consult identity provider specific docs if attempting to ensure
|
||||
// that the user controls the returned email address.
|
||||
//
|
||||
// See: https://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims
|
||||
ScopeEmail = "email"
|
||||
|
||||
// ScopeOfflineAccess is an optional scope defined by OpenID Connect for requesting
|
||||
// OAuth2 refresh tokens.
|
||||
//
|
||||
@@ -92,7 +111,24 @@ func doRequest(ctx context.Context, req *http.Request) (*http.Response, error) {
|
||||
return client.Do(req.WithContext(ctx))
|
||||
}
|
||||
|
||||
// Provider represents an OpenID Connect server's configuration.
|
||||
// Provider represents an OpenID Connect server's configuration, fetched from
|
||||
// the discovery document.
|
||||
//
|
||||
// To access fields in the discovery document that aren't exposed directly
|
||||
// through this package's API, use the [Provider.Claims] method. For example, to
|
||||
// access the registration or end session endpoints:
|
||||
//
|
||||
// p, err := oidc.NewProvider(ctx, "https://issuer.example.com")
|
||||
// if err != nil {
|
||||
// // ...
|
||||
// }
|
||||
// var metadata struct {
|
||||
// EndSessionEndpoint string `json:"end_session_endpoint"`
|
||||
// RegistrationEndpoint string `json:"registration_endpoint"`
|
||||
// }
|
||||
// if err := p.Claims(&metadata); err != nil {
|
||||
// // ...
|
||||
// }
|
||||
type Provider struct {
|
||||
issuer string
|
||||
authURL string
|
||||
@@ -213,6 +249,8 @@ type ProviderConfig struct {
|
||||
//
|
||||
// The provided context is only used for [http.Client] configuration through
|
||||
// [ClientContext], not cancelation.
|
||||
//
|
||||
// For providers that implement discovery, use [NewProvider] instead.
|
||||
func (p *ProviderConfig) NewProvider(ctx context.Context) *Provider {
|
||||
return &Provider{
|
||||
issuer: p.IssuerURL,
|
||||
@@ -226,12 +264,36 @@ func (p *ProviderConfig) NewProvider(ctx context.Context) *Provider {
|
||||
}
|
||||
}
|
||||
|
||||
// IssuerMismatchError is returned by [NewProvider] when the "iss" value
|
||||
// reported by the upstream is different than the expected value.
|
||||
//
|
||||
// Issuer mismatches can occur due to trailing slashes ("https://example.com"
|
||||
// vs. "https://example.com/") or represent significant misconfiguration for
|
||||
// multi-tenant issuers.
|
||||
//
|
||||
// Issuers must match exactly as they are also used to validate ID Tokens.
|
||||
//
|
||||
// https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
|
||||
type IssuerMismatchError struct {
|
||||
// The value provided to this package. The expected value.
|
||||
Provided string
|
||||
// The value advertised by the discovery document.
|
||||
Discovered string
|
||||
}
|
||||
|
||||
func (e *IssuerMismatchError) Error() string {
|
||||
return fmt.Sprintf("oidc: issuer URL provided to client (%q) did not match the issuer URL returned by provider (%q)", e.Provided, e.Discovered)
|
||||
}
|
||||
|
||||
// NewProvider uses the OpenID Connect discovery mechanism to construct a Provider.
|
||||
// The issuer is the URL identifier for the service. For example: "https://accounts.google.com"
|
||||
// or "https://login.salesforce.com".
|
||||
//
|
||||
// If the "iss" value returned in the discovery document doesn't match the value
|
||||
// provided here, [IssuerMismatchError] is returned.
|
||||
//
|
||||
// OpenID Connect providers that don't implement discovery or host the discovery
|
||||
// document at a non-spec complaint path (such as requiring a URL parameter),
|
||||
// document at a non-spec compliant path (such as requiring a URL parameter),
|
||||
// should use [ProviderConfig] instead.
|
||||
//
|
||||
// See: https://openid.net/specs/openid-connect-discovery-1_0.html
|
||||
@@ -267,7 +329,10 @@ func NewProvider(ctx context.Context, issuer string) (*Provider, error) {
|
||||
issuerURL = issuer
|
||||
}
|
||||
if p.Issuer != issuerURL && !skipIssuerValidation {
|
||||
return nil, fmt.Errorf("oidc: issuer URL provided to client (%q) did not match the issuer URL returned by provider (%q)", issuer, p.Issuer)
|
||||
return nil, &IssuerMismatchError{
|
||||
Provided: issuerURL,
|
||||
Discovered: p.Issuer,
|
||||
}
|
||||
}
|
||||
var algs []string
|
||||
for _, a := range p.Algorithms {
|
||||
@@ -301,7 +366,7 @@ func NewProvider(ctx context.Context, issuer string) (*Provider, error) {
|
||||
//
|
||||
// For a list of fields defined by the OpenID Connect spec see:
|
||||
// https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
|
||||
func (p *Provider) Claims(v interface{}) error {
|
||||
func (p *Provider) Claims(v any) error {
|
||||
if p.rawClaims == nil {
|
||||
return errors.New("oidc: claims not set")
|
||||
}
|
||||
@@ -340,7 +405,7 @@ type userInfoRaw struct {
|
||||
}
|
||||
|
||||
// Claims unmarshals the raw JSON object claims into the provided object.
|
||||
func (u *UserInfo) Claims(v interface{}) error {
|
||||
func (u *UserInfo) Claims(v any) error {
|
||||
if u.claims == nil {
|
||||
return errors.New("oidc: claims not set")
|
||||
}
|
||||
@@ -348,6 +413,44 @@ func (u *UserInfo) Claims(v interface{}) error {
|
||||
}
|
||||
|
||||
// UserInfo uses the token source to query the provider's user info endpoint.
|
||||
//
|
||||
// It's fewer round trips and better supported to validate the ID Token with
|
||||
// [Provider.Verifier], rather than using the UserInfo endpoint. The ID Token
|
||||
// contains all information [UserInfo] provides:
|
||||
//
|
||||
// p, err := oidc.NewProvider(ctx, "https://issuer.example.com")
|
||||
// if err != nil {
|
||||
// // ...
|
||||
// }
|
||||
// config := &oidc.Config{
|
||||
// ClientID: clientID,
|
||||
// }
|
||||
// v := p.Verifier(config)
|
||||
// http.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
|
||||
// oauth2Token, err := config.Exchange(ctx, r.URL.Query().Get("code"))
|
||||
// if err != nil {
|
||||
// // ...
|
||||
// }
|
||||
// rawIDToken, ok := oauth2Token.Extra("id_token").(string)
|
||||
// if !ok {
|
||||
// // ...
|
||||
// }
|
||||
// idToken, err := verifier.Verify(ctx, rawIDToken)
|
||||
// if err != nil {
|
||||
// // ...
|
||||
// }
|
||||
// // https://openid.net/specs/openid-connect-core-1_0.html#Claims
|
||||
// var claims struct {
|
||||
// Email string `json:"email"`
|
||||
// EmailVerified bool `json:"email_verified"`
|
||||
// Name string `json:"name"`
|
||||
// Picture string `json:"picture"`
|
||||
// }
|
||||
// if err := idToken.Claims(&claims); err != nil {
|
||||
// // ...
|
||||
// }
|
||||
// // Use claims...
|
||||
// })
|
||||
func (p *Provider) UserInfo(ctx context.Context, tokenSource oauth2.TokenSource) (*UserInfo, error) {
|
||||
if p.userInfoURL == "" {
|
||||
return nil, errors.New("oidc: user info endpoint is not supported by this provider")
|
||||
@@ -425,7 +528,7 @@ type IDToken struct {
|
||||
// A unique string which identifies the end user.
|
||||
Subject string
|
||||
|
||||
// Expiry of the token. Ths package will not process tokens that have
|
||||
// Expiry of the token. This package will not process tokens that have
|
||||
// expired unless that validation is explicitly turned off.
|
||||
Expiry time.Time
|
||||
// When the token was issued by the provider.
|
||||
@@ -433,7 +536,7 @@ type IDToken struct {
|
||||
|
||||
// Initial nonce provided during the authentication redirect.
|
||||
//
|
||||
// This package does NOT provided verification on the value of this field
|
||||
// This package does NOT provide verification on the value of this field
|
||||
// and it's the user's responsibility to ensure it contains a valid value.
|
||||
Nonce string
|
||||
|
||||
@@ -465,15 +568,15 @@ type IDToken struct {
|
||||
// if err := idToken.Claims(&claims); err != nil {
|
||||
// // handle error
|
||||
// }
|
||||
func (i *IDToken) Claims(v interface{}) error {
|
||||
func (i *IDToken) Claims(v any) error {
|
||||
if i.claims == nil {
|
||||
return errors.New("oidc: claims not set")
|
||||
}
|
||||
return json.Unmarshal(i.claims, v)
|
||||
}
|
||||
|
||||
// VerifyAccessToken verifies that the hash of the access token that corresponds to the iD token
|
||||
// matches the hash in the id token. It returns an error if the hashes don't match.
|
||||
// VerifyAccessToken verifies that the hash of the access token that corresponds to the ID token
|
||||
// matches the hash in the ID token. It returns an error if the hashes don't match.
|
||||
// It is the caller's responsibility to ensure that the optional access token hash is present for the ID token
|
||||
// before calling this method. See https://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
|
||||
func (i *IDToken) VerifyAccessToken(accessToken string) error {
|
||||
@@ -570,7 +673,7 @@ func (j *jsonTime) UnmarshalJSON(b []byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func unmarshalResp(r *http.Response, body []byte, v interface{}) error {
|
||||
func unmarshalResp(r *http.Response, body []byte, v any) error {
|
||||
err := json.Unmarshal(body, &v)
|
||||
if err == nil {
|
||||
return nil
|
||||
|
||||
+17
-24
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
jose "github.com/go-jose/go-jose/v4"
|
||||
@@ -17,10 +18,10 @@ const (
|
||||
issuerGoogleAccountsNoScheme = "accounts.google.com"
|
||||
)
|
||||
|
||||
// TokenExpiredError indicates that Verify or VerifyLogout failed because the
|
||||
// token was expired. This error does NOT indicate that the token is not also
|
||||
// invalid for other reasons. Other checks might have failed if the expiration
|
||||
// check had not failed.
|
||||
// TokenExpiredError indicates that [IDTokenVerifier.Verify] or
|
||||
// [IDTokenVerifier.VerifyLogout] failed because the token was expired. This
|
||||
// error does NOT indicate that the token is not also invalid for other reasons.
|
||||
// Other checks might have failed if the expiration check had not failed.
|
||||
type TokenExpiredError struct {
|
||||
// Expiry is the time when the token expired.
|
||||
Expiry time.Time
|
||||
@@ -30,7 +31,7 @@ func (e *TokenExpiredError) Error() string {
|
||||
return fmt.Sprintf("oidc: token is expired (Token Expiry: %v)", e.Expiry)
|
||||
}
|
||||
|
||||
// KeySet is a set of publc JSON Web Keys that can be used to validate the signature
|
||||
// KeySet is a set of public JSON Web Keys that can be used to validate the signature
|
||||
// of JSON web tokens. This is expected to be backed by a remote key set through
|
||||
// provider metadata discovery or an in-memory set of keys delivered out-of-band.
|
||||
type KeySet interface {
|
||||
@@ -55,8 +56,8 @@ type IDTokenVerifier struct {
|
||||
// NewVerifier returns a verifier manually constructed from a key set and issuer URL.
|
||||
//
|
||||
// It's easier to use provider discovery to construct an IDTokenVerifier than creating
|
||||
// one directly. This method is intended to be used with provider that don't support
|
||||
// metadata discovery, or avoiding round trips when the key set URL is already known.
|
||||
// one directly. This method is intended to be used with providers that don't support
|
||||
// metadata discovery, or to avoid round trips when the key set URL is already known.
|
||||
//
|
||||
// This constructor can be used to create a verifier directly using the issuer URL and
|
||||
// JSON Web Key Set URL without using discovery:
|
||||
@@ -82,8 +83,8 @@ type Config struct {
|
||||
ClientID string
|
||||
// If specified, only this set of algorithms may be used to sign the JWT.
|
||||
//
|
||||
// If the IDTokenVerifier is created from a provider with (*Provider).Verifier, this
|
||||
// defaults to the set of algorithms the provider supports. Otherwise this values
|
||||
// If the IDTokenVerifier is created from a provider with [Provider.Verifier], this
|
||||
// defaults to the set of algorithms the provider supports. Otherwise this value
|
||||
// defaults to RS256.
|
||||
SupportedSigningAlgs []string
|
||||
|
||||
@@ -92,7 +93,7 @@ type Config struct {
|
||||
// If true, token expiry is not checked.
|
||||
SkipExpiryCheck bool
|
||||
|
||||
// SkipIssuerCheck is intended for specialized cases where the the caller wishes to
|
||||
// SkipIssuerCheck is intended for specialized cases where the caller wishes to
|
||||
// defer issuer validation. When enabled, callers MUST independently verify the Token's
|
||||
// Issuer is a known good value.
|
||||
//
|
||||
@@ -117,8 +118,9 @@ type Config struct {
|
||||
}
|
||||
|
||||
// VerifierContext returns an IDTokenVerifier that uses the provider's key set to
|
||||
// verify JWTs. As opposed to Verifier, the context is used to configure requests
|
||||
// to the upstream JWKs endpoint. The provided context's cancellation is ignored.
|
||||
// verify JWTs. As opposed to [Provider.Verifier], the context is used to configure
|
||||
// requests to the upstream JWKs endpoint. The provided context's cancellation is
|
||||
// ignored.
|
||||
func (p *Provider) VerifierContext(ctx context.Context, config *Config) *IDTokenVerifier {
|
||||
return p.newVerifier(NewRemoteKeySet(ctx, p.jwksURL), config)
|
||||
}
|
||||
@@ -126,7 +128,7 @@ func (p *Provider) VerifierContext(ctx context.Context, config *Config) *IDToken
|
||||
// Verifier returns an IDTokenVerifier that uses the provider's key set to verify JWTs.
|
||||
//
|
||||
// The returned verifier uses a background context for all requests to the upstream
|
||||
// JWKs endpoint. To control that context, use VerifierContext instead.
|
||||
// JWKs endpoint. To control that context, use [Provider.VerifierContext] instead.
|
||||
func (p *Provider) Verifier(config *Config) *IDTokenVerifier {
|
||||
return p.newVerifier(p.remoteKeySet(), config)
|
||||
}
|
||||
@@ -142,15 +144,6 @@ func (p *Provider) newVerifier(keySet KeySet, config *Config) *IDTokenVerifier {
|
||||
return NewVerifier(p.issuer, keySet, config)
|
||||
}
|
||||
|
||||
func contains(sli []string, ele string) bool {
|
||||
for _, s := range sli {
|
||||
if s == ele {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Returns the Claims from the distributed JWT token
|
||||
func resolveDistributedClaim(ctx context.Context, verifier *IDTokenVerifier, src claimSource) ([]byte, error) {
|
||||
req, err := http.NewRequest("GET", src.Endpoint, nil)
|
||||
@@ -187,7 +180,7 @@ func resolveDistributedClaim(ctx context.Context, verifier *IDTokenVerifier, src
|
||||
// Verify parses a raw ID Token, verifies it's been signed by the provider, performs
|
||||
// any additional checks depending on the Config, and returns the payload.
|
||||
//
|
||||
// Verify does NOT do nonce validation, which is the callers responsibility.
|
||||
// Verify does NOT do nonce validation, which is the caller's responsibility.
|
||||
//
|
||||
// See: https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
|
||||
//
|
||||
@@ -257,7 +250,7 @@ func (v *IDTokenVerifier) Verify(ctx context.Context, rawIDToken string) (*IDTok
|
||||
// This check DOES NOT ensure that the ClientID is the party to which the ID Token was issued (i.e. Authorized party).
|
||||
if !v.config.SkipClientIDCheck {
|
||||
if v.config.ClientID != "" {
|
||||
if !contains(t.Audience, v.config.ClientID) {
|
||||
if !slices.Contains(t.Audience, v.config.ClientID) {
|
||||
return nil, fmt.Errorf("oidc: expected audience %q got %q", v.config.ClientID, t.Audience)
|
||||
}
|
||||
} else {
|
||||
|
||||
+23
-10
@@ -19,6 +19,10 @@ import (
|
||||
// no limit.
|
||||
var MaxPacketLengthBytes int64 = math.MaxInt32
|
||||
|
||||
// MaxNestingDepth specifies the maximum allowed nesting depth when calling ReadPacket, DecodePacket, or
|
||||
// DecodePacketErr. Set to 0 for no limit.
|
||||
var MaxNestingDepth int = 1000
|
||||
|
||||
type Packet struct {
|
||||
Identifier
|
||||
Value interface{}
|
||||
@@ -218,7 +222,7 @@ func printPacket(out io.Writer, p *Packet, indent int, printBytes bool) {
|
||||
|
||||
// ReadPacket reads a single Packet from the reader.
|
||||
func ReadPacket(reader io.Reader) (*Packet, error) {
|
||||
p, _, err := readPacket(reader)
|
||||
p, _, err := readPacket(reader, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -278,7 +282,7 @@ func int64Length(i int64) (numBytes int) {
|
||||
// DecodePacket decodes the given bytes into a single Packet
|
||||
// If a decode error is encountered, nil is returned.
|
||||
func DecodePacket(data []byte) *Packet {
|
||||
p, _, _ := readPacket(bytes.NewBuffer(data))
|
||||
p, _, _ := readPacket(bytes.NewBuffer(data), 0)
|
||||
|
||||
return p
|
||||
}
|
||||
@@ -286,7 +290,7 @@ func DecodePacket(data []byte) *Packet {
|
||||
// DecodePacketErr decodes the given bytes into a single Packet
|
||||
// If a decode error is encountered, nil is returned.
|
||||
func DecodePacketErr(data []byte) (*Packet, error) {
|
||||
p, _, err := readPacket(bytes.NewBuffer(data))
|
||||
p, _, err := readPacket(bytes.NewBuffer(data), 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -294,12 +298,20 @@ func DecodePacketErr(data []byte) (*Packet, error) {
|
||||
}
|
||||
|
||||
// readPacket reads a single Packet from the reader, returning the number of bytes read.
|
||||
func readPacket(reader io.Reader) (*Packet, int, error) {
|
||||
func readPacket(reader io.Reader, depth int) (*Packet, int, error) {
|
||||
if MaxNestingDepth > 0 && depth >= MaxNestingDepth {
|
||||
return nil, 0, fmt.Errorf("nesting depth %d exceeds maximum %d", depth, MaxNestingDepth)
|
||||
}
|
||||
|
||||
identifier, length, read, err := readHeader(reader)
|
||||
if err != nil {
|
||||
return nil, read, err
|
||||
}
|
||||
|
||||
if length != LengthIndefinite && MaxPacketLengthBytes > 0 && int64(length) > MaxPacketLengthBytes {
|
||||
return nil, read, fmt.Errorf("length %d greater than maximum %d", length, MaxPacketLengthBytes)
|
||||
}
|
||||
|
||||
p := &Packet{
|
||||
Identifier: identifier,
|
||||
}
|
||||
@@ -326,13 +338,19 @@ func readPacket(reader io.Reader) (*Packet, int, error) {
|
||||
}
|
||||
|
||||
// Read the next packet
|
||||
child, r, err := readPacket(reader)
|
||||
child, r, err := readPacket(reader, depth+1)
|
||||
if err != nil {
|
||||
return nil, read, unexpectedEOF(err)
|
||||
}
|
||||
contentRead += r
|
||||
read += r
|
||||
|
||||
// Enforce the aggregate size limit for constructed packets. Indefinite length declares
|
||||
// no bound up front, so the content bytes are only known as they are read.
|
||||
if MaxPacketLengthBytes > 0 && int64(contentRead) > MaxPacketLengthBytes {
|
||||
return nil, read, fmt.Errorf("length %d greater than maximum %d", contentRead, MaxPacketLengthBytes)
|
||||
}
|
||||
|
||||
// Test is this is the EOC marker for our packet
|
||||
if isEOCPacket(child) {
|
||||
if length == LengthIndefinite {
|
||||
@@ -351,11 +369,6 @@ func readPacket(reader io.Reader) (*Packet, int, error) {
|
||||
return nil, read, errors.New("indefinite length used with primitive type")
|
||||
}
|
||||
|
||||
// Read definite-length content
|
||||
if MaxPacketLengthBytes > 0 && int64(length) > MaxPacketLengthBytes {
|
||||
return nil, read, fmt.Errorf("length %d greater than maximum %d", length, MaxPacketLengthBytes)
|
||||
}
|
||||
|
||||
var content []byte
|
||||
if length > 0 {
|
||||
// Read the content and limit it to the parsed length.
|
||||
|
||||
+5
-4
@@ -40,7 +40,7 @@ func readLength(reader io.Reader) (length int, read int, err error) {
|
||||
}
|
||||
|
||||
// Accumulate into a 64-bit variable
|
||||
var length64 int64
|
||||
var length64 uint64
|
||||
for i := 0; i < lengthBytes; i++ {
|
||||
b, err = readByte(reader)
|
||||
if err != nil {
|
||||
@@ -53,13 +53,14 @@ func readLength(reader io.Reader) (length int, read int, err error) {
|
||||
|
||||
// x.600, 8.1.3.5
|
||||
length64 <<= 8
|
||||
length64 |= int64(b)
|
||||
length64 |= uint64(b)
|
||||
}
|
||||
|
||||
// Cast to a platform-specific integer
|
||||
length = int(length64)
|
||||
// Ensure we didn't overflow
|
||||
if int64(length) != length64 {
|
||||
// Ensure we didn't overflow or wrap negative. Length octets are unsigned
|
||||
// (x.600, 8.1.3.5), so a negative result is unrepresentable, not indefinite.
|
||||
if length < 0 || uint64(length) != length64 {
|
||||
return 0, read, errors.New("long-form length overflow")
|
||||
}
|
||||
|
||||
|
||||
+1
@@ -221,6 +221,7 @@ type Router interface {
|
||||
Patch(pattern string, h http.HandlerFunc)
|
||||
Post(pattern string, h http.HandlerFunc)
|
||||
Put(pattern string, h http.HandlerFunc)
|
||||
Query(pattern string, h http.HandlerFunc)
|
||||
Trace(pattern string, h http.HandlerFunc)
|
||||
|
||||
// NotFound defines a handler to respond whenever a route could
|
||||
|
||||
+1
@@ -102,6 +102,7 @@ type Router interface {
|
||||
Patch(pattern string, h http.HandlerFunc)
|
||||
Post(pattern string, h http.HandlerFunc)
|
||||
Put(pattern string, h http.HandlerFunc)
|
||||
Query(pattern string, h http.HandlerFunc)
|
||||
Trace(pattern string, h http.HandlerFunc)
|
||||
|
||||
// NotFound defines a handler to respond whenever a route could
|
||||
|
||||
+2
@@ -23,6 +23,8 @@ var defaultCompressibleContentTypes = []string{
|
||||
"application/json",
|
||||
"application/atom+xml",
|
||||
"application/rss+xml",
|
||||
"application/xml",
|
||||
"text/xml",
|
||||
"image/svg+xml",
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -166,7 +166,7 @@ func (l *defaultLogEntry) Write(status, bytes int, header http.Header, elapsed t
|
||||
}
|
||||
|
||||
func (l *defaultLogEntry) Panic(v interface{}, stack []byte) {
|
||||
PrintPrettyStack(v)
|
||||
printPrettyStack(v, l.useColor)
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
||||
-1
@@ -1,5 +1,4 @@
|
||||
//go:build !tinygo
|
||||
// +build !tinygo
|
||||
|
||||
package middleware
|
||||
|
||||
|
||||
+9
-3
@@ -52,9 +52,16 @@ func Recoverer(next http.Handler) http.Handler {
|
||||
var recovererErrorWriter io.Writer = os.Stderr
|
||||
|
||||
func PrintPrettyStack(rvr interface{}) {
|
||||
printPrettyStack(rvr, true)
|
||||
}
|
||||
|
||||
// printPrettyStack prints a formatted stack trace to stderr. When useColor is
|
||||
// false, ANSI colour codes are suppressed, which is useful for terminals that
|
||||
// do not support them (e.g. on Windows) or when output is being captured.
|
||||
func printPrettyStack(rvr interface{}, useColor bool) {
|
||||
debugStack := debug.Stack()
|
||||
s := prettyStack{}
|
||||
out, err := s.parse(debugStack, rvr)
|
||||
out, err := s.parse(debugStack, rvr, useColor)
|
||||
if err == nil {
|
||||
recovererErrorWriter.Write(out)
|
||||
} else {
|
||||
@@ -66,9 +73,8 @@ func PrintPrettyStack(rvr interface{}) {
|
||||
type prettyStack struct {
|
||||
}
|
||||
|
||||
func (s prettyStack) parse(debugStack []byte, rvr interface{}) ([]byte, error) {
|
||||
func (s prettyStack) parse(debugStack []byte, rvr interface{}, useColor bool) ([]byte, error) {
|
||||
var err error
|
||||
useColor := true
|
||||
buf := &bytes.Buffer{}
|
||||
|
||||
cW(buf, false, bRed, "\n")
|
||||
|
||||
+6
-4
@@ -207,10 +207,12 @@ func (f *http2FancyWriter) Push(target string, opts *http.PushOptions) error {
|
||||
}
|
||||
|
||||
func (f *httpFancyWriter) ReadFrom(r io.Reader) (int64, error) {
|
||||
if f.basicWriter.tee != nil {
|
||||
// Route through basicWriter.Write so that data is also written to the
|
||||
// tee writer. basicWriter.Write already increments basicWriter.bytes,
|
||||
// so we must NOT add n again here (that would double-count).
|
||||
if f.basicWriter.tee != nil || f.basicWriter.discard {
|
||||
// Route through basicWriter.Write so that the tee and discard semantics
|
||||
// are honored (the fast ReaderFrom path below would bypass both, writing
|
||||
// straight to the original ResponseWriter). basicWriter.Write already
|
||||
// increments basicWriter.bytes, so we must NOT add n again here (that
|
||||
// would double-count).
|
||||
n, err := io.Copy(&f.basicWriter, r)
|
||||
return n, err
|
||||
}
|
||||
|
||||
+6
@@ -186,6 +186,12 @@ func (mx *Mux) Put(pattern string, handlerFn http.HandlerFunc) {
|
||||
mx.handle(mPUT, pattern, handlerFn)
|
||||
}
|
||||
|
||||
// Query adds the route `pattern` that matches a QUERY http method to
|
||||
// execute the `handlerFn` http.HandlerFunc.
|
||||
func (mx *Mux) Query(pattern string, handlerFn http.HandlerFunc) {
|
||||
mx.handle(mQUERY, pattern, handlerFn)
|
||||
}
|
||||
|
||||
// Trace adds the route `pattern` that matches a TRACE http method to
|
||||
// execute the `handlerFn` http.HandlerFunc.
|
||||
func (mx *Mux) Trace(pattern string, handlerFn http.HandlerFunc) {
|
||||
|
||||
+9
-1
@@ -26,11 +26,17 @@ const (
|
||||
mPATCH
|
||||
mPOST
|
||||
mPUT
|
||||
mQUERY
|
||||
mTRACE
|
||||
)
|
||||
|
||||
var mALL = mCONNECT | mDELETE | mGET | mHEAD |
|
||||
mOPTIONS | mPATCH | mPOST | mPUT | mTRACE
|
||||
mOPTIONS | mPATCH | mPOST | mPUT | mQUERY | mTRACE
|
||||
|
||||
// methodQuery is the HTTP QUERY method (RFC 10008), a safe, idempotent
|
||||
// method that conveys a request body. It is defined here until net/http
|
||||
// provides an equivalent constant, at which point this is a 1-1 swap.
|
||||
const methodQuery = "QUERY"
|
||||
|
||||
var methodMap = map[string]methodTyp{
|
||||
http.MethodConnect: mCONNECT,
|
||||
@@ -41,6 +47,7 @@ var methodMap = map[string]methodTyp{
|
||||
http.MethodPatch: mPATCH,
|
||||
http.MethodPost: mPOST,
|
||||
http.MethodPut: mPUT,
|
||||
methodQuery: mQUERY,
|
||||
http.MethodTrace: mTRACE,
|
||||
}
|
||||
|
||||
@@ -53,6 +60,7 @@ var reverseMethodMap = map[methodTyp]string{
|
||||
mPATCH: http.MethodPatch,
|
||||
mPOST: http.MethodPost,
|
||||
mPUT: http.MethodPut,
|
||||
mQUERY: methodQuery,
|
||||
mTRACE: http.MethodTrace,
|
||||
}
|
||||
|
||||
|
||||
+3
@@ -83,6 +83,9 @@ func (l *Conn) Add(addRequest *AddRequest) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(packet.Children) < 2 {
|
||||
return fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
|
||||
}
|
||||
if packet.Children[1].Tag == ApplicationAddResponse {
|
||||
err := GetLDAPError(packet)
|
||||
if err != nil {
|
||||
|
||||
+61
-16
@@ -3,13 +3,13 @@ package ldap
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/md5"
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
enchex "encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"math/rand"
|
||||
"strings"
|
||||
"unicode/utf16"
|
||||
|
||||
@@ -221,12 +221,15 @@ func (l *Conn) DigestMD5Bind(digestMD5BindRequest *DigestMD5BindRequest) (*Diges
|
||||
}
|
||||
|
||||
if len(params) > 0 {
|
||||
resp := computeResponse(
|
||||
resp, err := computeResponse(
|
||||
params,
|
||||
"ldap/"+strings.ToLower(digestMD5BindRequest.Host),
|
||||
digestMD5BindRequest.Username,
|
||||
digestMD5BindRequest.Password,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("compute digest-md5 response: %s", err)
|
||||
}
|
||||
packet = ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "LDAP Request")
|
||||
packet.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, l.nextMessageID(), "MessageID"))
|
||||
|
||||
@@ -291,12 +294,22 @@ func parseParams(str string) (map[string]string, error) {
|
||||
m := make(map[string]string)
|
||||
var key, value string
|
||||
var state int
|
||||
var escaped bool
|
||||
for i := 0; i <= len(str); i++ {
|
||||
switch state {
|
||||
case 0: // reading key
|
||||
if i == len(str) {
|
||||
return nil, fmt.Errorf("syntax error on %d", i)
|
||||
}
|
||||
// The digest-challenge is an RFC 2068 #rule (RFC 2831 section 2.1.1),
|
||||
// which permits optional linear whitespace around the comma directive
|
||||
// separators. Directive names are tokens that never contain
|
||||
// whitespace, so skip it here; otherwise a directive following
|
||||
// "..., name" is keyed with a leading space and the lookups in
|
||||
// computeResponse (realm, nonce, authzid) miss it.
|
||||
if str[i] == ' ' || str[i] == '\t' {
|
||||
continue
|
||||
}
|
||||
if str[i] != '=' {
|
||||
key += string(str[i])
|
||||
continue
|
||||
@@ -307,6 +320,14 @@ func parseParams(str string) (map[string]string, error) {
|
||||
m[key] = value
|
||||
break
|
||||
}
|
||||
// Linear whitespace outside a quoted string is not part of the
|
||||
// value: an unquoted value is a token and a quoted value's content
|
||||
// is read in the quoted state below. Skipping it lets a challenge
|
||||
// using the whitespace the #rule allows (e.g. `nonce="n" , qop=auth`)
|
||||
// parse the same as the unspaced form.
|
||||
if str[i] == ' ' || str[i] == '\t' {
|
||||
continue
|
||||
}
|
||||
switch str[i] {
|
||||
case ',':
|
||||
m[key] = value
|
||||
@@ -325,20 +346,34 @@ func parseParams(str string) (map[string]string, error) {
|
||||
if i == len(str) {
|
||||
return nil, fmt.Errorf("syntax error on %d", i)
|
||||
}
|
||||
if str[i] != '"' {
|
||||
switch {
|
||||
case escaped:
|
||||
// RFC 2831 section 7.1 quoted-pair: a backslash escapes the
|
||||
// following character, so the next byte is taken literally
|
||||
// (this is how a server sends a literal " or \ in a realm or
|
||||
// nonce).
|
||||
value += string(str[i])
|
||||
} else {
|
||||
escaped = false
|
||||
case str[i] == '\\':
|
||||
escaped = true
|
||||
case str[i] == '"':
|
||||
state = 1
|
||||
default:
|
||||
value += string(str[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func computeResponse(params map[string]string, uri, username, password string) string {
|
||||
func computeResponse(params map[string]string, uri, username, password string) (string, error) {
|
||||
nc := "00000001"
|
||||
qop := "auth"
|
||||
cnonce := enchex.EncodeToString(randomBytes(16))
|
||||
rb, err := randomBytes(16)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
cnonce := enchex.EncodeToString(rb)
|
||||
x := username + ":" + params["realm"] + ":" + password
|
||||
y := md5Hash([]byte(x))
|
||||
|
||||
@@ -361,14 +396,24 @@ func computeResponse(params map[string]string, uri, username, password string) s
|
||||
resp := enchex.EncodeToString(md5Hash([]byte(kd)))
|
||||
return fmt.Sprintf(
|
||||
`username="%s",realm="%s",nonce="%s",cnonce="%s",nc=00000001,qop=%s,digest-uri="%s",response=%s`,
|
||||
username,
|
||||
params["realm"],
|
||||
params["nonce"],
|
||||
quotedStringEscape(username),
|
||||
quotedStringEscape(params["realm"]),
|
||||
quotedStringEscape(params["nonce"]),
|
||||
cnonce,
|
||||
qop,
|
||||
uri,
|
||||
quotedStringEscape(uri),
|
||||
resp,
|
||||
)
|
||||
), nil
|
||||
}
|
||||
|
||||
// quotedStringEscape escapes the two characters that may not appear unescaped
|
||||
// inside a DIGEST-MD5 quoted string per RFC 2831 section 7.1: the backslash
|
||||
// and the double quote. The backslash is replaced first so the quotes escaped
|
||||
// afterwards are not doubled.
|
||||
func quotedStringEscape(s string) string {
|
||||
s = strings.ReplaceAll(s, `\`, `\\`)
|
||||
s = strings.ReplaceAll(s, `"`, `\"`)
|
||||
return s
|
||||
}
|
||||
|
||||
func md5Hash(b []byte) []byte {
|
||||
@@ -377,12 +422,12 @@ func md5Hash(b []byte) []byte {
|
||||
return hasher.Sum(nil)
|
||||
}
|
||||
|
||||
func randomBytes(len int) []byte {
|
||||
b := make([]byte, len)
|
||||
for i := 0; i < len; i++ {
|
||||
b[i] = byte(rand.Intn(256))
|
||||
func randomBytes(length int) ([]byte, error) {
|
||||
b := make([]byte, length)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return b
|
||||
return b, nil
|
||||
}
|
||||
|
||||
var externalBindRequest = requestFunc(func(envelope *ber.Packet) error {
|
||||
|
||||
+3
@@ -46,6 +46,9 @@ func (l *Conn) Compare(dn, attribute, value string) (bool, error) {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if len(packet.Children) < 2 {
|
||||
return false, fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
|
||||
}
|
||||
if packet.Children[1].Tag == ApplicationCompareResponse {
|
||||
err := GetLDAPError(packet)
|
||||
|
||||
|
||||
+55
-11
@@ -8,6 +8,7 @@ import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
@@ -112,7 +113,11 @@ type Conn struct {
|
||||
outstandingRequests uint
|
||||
messageMutex sync.Mutex
|
||||
|
||||
err error
|
||||
// errMutex guards err only. It is a leaf lock: processMessages and reader
|
||||
// record errors while another goroutine may hold messageMutex, so err must
|
||||
// not share messageMutex or those writers could deadlock.
|
||||
errMutex sync.Mutex
|
||||
err error
|
||||
}
|
||||
|
||||
var _ Client = &Conn{}
|
||||
@@ -160,10 +165,18 @@ type DialContext struct {
|
||||
|
||||
func (dc *DialContext) dial(u *url.URL) (net.Conn, error) {
|
||||
if u.Scheme == "ldapi" {
|
||||
if u.Path == "" || u.Path == "/" {
|
||||
u.Path = "/var/run/slapd/ldapi"
|
||||
// RFC 4516 (and draft-chu-ldap-ldapi) put the socket path in the
|
||||
// host component, percent-encoded; the path is an optional DN.
|
||||
// parseLDAPURL has already decoded the host. Accept the older
|
||||
// ldapi:///path form too so existing callers keep working.
|
||||
path := u.Host
|
||||
if path == "" {
|
||||
path = u.Path
|
||||
}
|
||||
return dc.dialer.Dial("unix", u.Path)
|
||||
if path == "" || path == "/" {
|
||||
path = "/var/run/slapd/ldapi"
|
||||
}
|
||||
return dc.dialer.Dial("unix", path)
|
||||
}
|
||||
|
||||
host, port, err := net.SplitHostPort(u.Host)
|
||||
@@ -222,12 +235,33 @@ func DialTLS(network, addr string, config *tls.Config) (*Conn, error) {
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
// parseLDAPURL parses an LDAP URL. It defers to net/url for the common
|
||||
// ldap/ldaps/cldap schemes, but handles ldapi specially: the spec puts the
|
||||
// unix socket path in the host, percent-encoded with %2F, and net/url rejects
|
||||
// that as invalid. Pull the host out manually and decode it.
|
||||
func parseLDAPURL(addr string) (*url.URL, error) {
|
||||
const ldapi = "ldapi://"
|
||||
if !strings.HasPrefix(addr, ldapi) {
|
||||
return url.Parse(addr)
|
||||
}
|
||||
rest := addr[len(ldapi):]
|
||||
host, path := rest, ""
|
||||
if i := strings.IndexByte(rest, '/'); i >= 0 {
|
||||
host, path = rest[:i], rest[i:]
|
||||
}
|
||||
decodedHost, err := url.PathUnescape(host)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ldapi: invalid host %q: %w", host, err)
|
||||
}
|
||||
return &url.URL{Scheme: "ldapi", Host: decodedHost, Path: path}, nil
|
||||
}
|
||||
|
||||
// DialURL connects to the given ldap URL.
|
||||
// The following schemas are supported: ldap://, ldaps://, ldapi://,
|
||||
// and cldap:// (RFC1798, deprecated but used by Active Directory).
|
||||
// On success a new Conn for the connection is returned.
|
||||
func DialURL(addr string, opts ...DialOpt) (*Conn, error) {
|
||||
u, err := url.Parse(addr)
|
||||
u, err := parseLDAPURL(addr)
|
||||
if err != nil {
|
||||
return nil, NewError(ErrorNetwork, err)
|
||||
}
|
||||
@@ -338,11 +372,21 @@ func (l *Conn) nextMessageID() int64 {
|
||||
// GetLastError returns the last recorded error from goroutines like processMessages and reader.
|
||||
// Only the last recorded error will be returned.
|
||||
func (l *Conn) GetLastError() error {
|
||||
l.messageMutex.Lock()
|
||||
defer l.messageMutex.Unlock()
|
||||
l.errMutex.Lock()
|
||||
defer l.errMutex.Unlock()
|
||||
return l.err
|
||||
}
|
||||
|
||||
// setError records the connection's last error. The background goroutines that
|
||||
// call it (processMessages, reader, the per-request timeout helper and the
|
||||
// SearchAsync worker) run concurrently with callers of GetLastError, so the
|
||||
// write must take the mutex the getter reads under.
|
||||
func (l *Conn) setError(err error) {
|
||||
l.errMutex.Lock()
|
||||
defer l.errMutex.Unlock()
|
||||
l.err = err
|
||||
}
|
||||
|
||||
// StartTLS sends the command to start a TLS session and then creates a new TLS Client
|
||||
func (l *Conn) StartTLS(config *tls.Config) error {
|
||||
if l.isTLS {
|
||||
@@ -491,7 +535,7 @@ func (l *Conn) sendProcessMessage(message *messagePacket) bool {
|
||||
func (l *Conn) processMessages() {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
l.err = fmt.Errorf("ldap: recovered panic in processMessages: %v", err)
|
||||
l.setError(fmt.Errorf("ldap: recovered panic in processMessages: %v", err))
|
||||
}
|
||||
for messageID, msgCtx := range l.messageContexts {
|
||||
// If we are closing due to an error, inform anyone who
|
||||
@@ -541,7 +585,7 @@ func (l *Conn) processMessages() {
|
||||
timer := time.NewTimer(time.Duration(requestTimeout))
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
l.err = fmt.Errorf("ldap: recovered panic in RequestTimeout: %v", err)
|
||||
l.setError(fmt.Errorf("ldap: recovered panic in RequestTimeout: %v", err))
|
||||
}
|
||||
|
||||
timer.Stop()
|
||||
@@ -563,7 +607,7 @@ func (l *Conn) processMessages() {
|
||||
if msgCtx, ok := l.messageContexts[message.MessageID]; ok {
|
||||
msgCtx.sendResponse(&PacketResponse{message.Packet, nil}, time.Duration(l.getTimeout()))
|
||||
} else {
|
||||
l.err = fmt.Errorf("ldap: received unexpected message %d, %v", message.MessageID, l.IsClosing())
|
||||
l.setError(fmt.Errorf("ldap: received unexpected message %d, %v", message.MessageID, l.IsClosing()))
|
||||
l.Debug.PrintPacket(message.Packet)
|
||||
}
|
||||
case MessageTimeout:
|
||||
@@ -590,7 +634,7 @@ func (l *Conn) reader() {
|
||||
cleanstop := false
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
l.err = fmt.Errorf("ldap: recovered panic in reader: %v", err)
|
||||
l.setError(fmt.Errorf("ldap: recovered panic in reader: %v", err))
|
||||
}
|
||||
if !cleanstop {
|
||||
l.Close()
|
||||
|
||||
+84
-27
@@ -565,12 +565,20 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
|
||||
case 1:
|
||||
// just type, no criticality or value
|
||||
packet.Children[0].Description = "Control Type (" + ControlTypeMap[ControlType] + ")"
|
||||
ControlType = packet.Children[0].Value.(string)
|
||||
ct, ok := packet.Children[0].Value.(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("control type is not a string: %T", packet.Children[0].Value)
|
||||
}
|
||||
ControlType = ct
|
||||
|
||||
case 2:
|
||||
packet.Children[0].Description = "Control Type (" + ControlTypeMap[ControlType] + ")"
|
||||
if packet.Children[0].Value != nil {
|
||||
ControlType = packet.Children[0].Value.(string)
|
||||
ct, ok := packet.Children[0].Value.(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("control type is not a string: %T", packet.Children[0].Value)
|
||||
}
|
||||
ControlType = ct
|
||||
} else if packet.Children[0].Data != nil {
|
||||
ControlType = packet.Children[0].Data.String()
|
||||
} else {
|
||||
@@ -579,9 +587,9 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
|
||||
|
||||
// Children[1] could be criticality or value (both are optional)
|
||||
// duck-type on whether this is a boolean
|
||||
if _, ok := packet.Children[1].Value.(bool); ok {
|
||||
if crit, ok := packet.Children[1].Value.(bool); ok {
|
||||
packet.Children[1].Description = "Criticality"
|
||||
Criticality = packet.Children[1].Value.(bool)
|
||||
Criticality = crit
|
||||
} else {
|
||||
packet.Children[1].Description = "Control Value"
|
||||
value = packet.Children[1]
|
||||
@@ -589,10 +597,18 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
|
||||
|
||||
case 3:
|
||||
packet.Children[0].Description = "Control Type (" + ControlTypeMap[ControlType] + ")"
|
||||
ControlType = packet.Children[0].Value.(string)
|
||||
ct, ok := packet.Children[0].Value.(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("control type is not a string: %T", packet.Children[0].Value)
|
||||
}
|
||||
ControlType = ct
|
||||
|
||||
packet.Children[1].Description = "Criticality"
|
||||
Criticality = packet.Children[1].Value.(bool)
|
||||
crit, ok := packet.Children[1].Value.(bool)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("criticality is not a bool: %T", packet.Children[1].Value)
|
||||
}
|
||||
Criticality = crit
|
||||
|
||||
packet.Children[2].Description = "Control Value"
|
||||
value = packet.Children[2]
|
||||
@@ -606,6 +622,9 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
|
||||
case ControlTypeManageDsaIT:
|
||||
return NewControlManageDsaIT(Criticality), nil
|
||||
case ControlTypePaging:
|
||||
if value == nil {
|
||||
return nil, fmt.Errorf("paging control value is missing")
|
||||
}
|
||||
value.Description += " (Paging)"
|
||||
c := new(ControlPaging)
|
||||
if value.Value != nil {
|
||||
@@ -617,11 +636,21 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
|
||||
value.Value = nil
|
||||
value.AppendChild(valueChildren)
|
||||
}
|
||||
if len(value.Children) == 0 {
|
||||
return nil, fmt.Errorf("paging control value is empty")
|
||||
}
|
||||
value = value.Children[0]
|
||||
value.Description = "Search Control Value"
|
||||
if len(value.Children) < 2 {
|
||||
return nil, fmt.Errorf("paging control value has %d children, expected 2", len(value.Children))
|
||||
}
|
||||
value.Children[0].Description = "Paging Size"
|
||||
value.Children[1].Description = "Cookie"
|
||||
c.PagingSize = uint32(value.Children[0].Value.(int64))
|
||||
pagingSize, ok := value.Children[0].Value.(int64)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("paging size is not an integer: %T", value.Children[0].Value)
|
||||
}
|
||||
c.PagingSize = uint32(pagingSize)
|
||||
c.Cookie = value.Children[1].Data.Bytes()
|
||||
value.Children[1].Value = c.Cookie
|
||||
return c, nil
|
||||
@@ -729,7 +758,16 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
|
||||
c.ControlType = ControlType
|
||||
c.Criticality = Criticality
|
||||
if value != nil {
|
||||
c.ControlValue = value.Value.(string)
|
||||
// A non-conforming or malicious server can send a non-string
|
||||
// (or nil) value here; the previous unchecked cast panicked
|
||||
// the calling goroutine, see #561. Fall back to the raw bytes
|
||||
// when the value isn't a string so we surface an error
|
||||
// instead of crashing.
|
||||
if s, ok := value.Value.(string); ok {
|
||||
c.ControlValue = s
|
||||
} else if value.Data != nil {
|
||||
c.ControlValue = value.Data.String()
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
@@ -921,28 +959,44 @@ func (c *ControlServerSideSorting) GetControlType() string {
|
||||
}
|
||||
|
||||
func NewControlServerSideSorting(value *ber.Packet) (*ControlServerSideSorting, error) {
|
||||
sortKeys := []*SortKey{}
|
||||
val, err := ber.DecodePacketErr(value.Data.Bytes())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode packet err: %s", err)
|
||||
}
|
||||
|
||||
val := value.Children[1].Children
|
||||
|
||||
if len(val) != 1 {
|
||||
if len(val.Children) == 0 {
|
||||
return nil, fmt.Errorf("no sequence value in packet")
|
||||
}
|
||||
|
||||
sequences := val[0].Children
|
||||
var sortKeys []*SortKey
|
||||
|
||||
for i, sequence := range sequences {
|
||||
sortKey := new(SortKey)
|
||||
|
||||
if len(sequence.Children) < 2 {
|
||||
return nil, fmt.Errorf("attributeType or matchingRule is missing from sequence %d", i)
|
||||
for i, sequence := range val.Children {
|
||||
if len(sequence.Children) < 1 || len(sequence.Children) > 3 {
|
||||
return nil, fmt.Errorf("attributeType is missing from sequence %d", i)
|
||||
}
|
||||
|
||||
sortKey.AttributeType = sequence.Children[0].Value.(string)
|
||||
sortKey.MatchingRule = sequence.Children[1].Value.(string)
|
||||
sortKey := new(SortKey)
|
||||
|
||||
if len(sequence.Children) == 3 {
|
||||
sortKey.Reverse = sequence.Children[2].Value.(bool)
|
||||
for _, child := range sequence.Children {
|
||||
switch {
|
||||
case child.ClassType == ber.ClassUniversal && child.Tag == ber.TagOctetString:
|
||||
// A constructed-form OCTET STRING matches this case but leaves
|
||||
// Value nil; guard the assertion so a malformed attributeType is
|
||||
// rejected below rather than panicking.
|
||||
if attrType, ok := child.Value.(string); ok {
|
||||
sortKey.AttributeType = attrType
|
||||
}
|
||||
|
||||
case child.ClassType == ber.ClassContext && child.Tag == 0:
|
||||
sortKey.MatchingRule = child.Data.String()
|
||||
|
||||
case child.ClassType == ber.ClassContext && child.Tag == 1:
|
||||
b := child.Data.Bytes()
|
||||
sortKey.Reverse = len(b) > 0 && b[0] != 0
|
||||
}
|
||||
}
|
||||
if sortKey.AttributeType == "" {
|
||||
return nil, fmt.Errorf("attributeType is missing from sequence %d", i)
|
||||
}
|
||||
|
||||
sortKeys = append(sortKeys, sortKey)
|
||||
@@ -959,7 +1013,6 @@ func (c *ControlServerSideSorting) Encode() *ber.Packet {
|
||||
packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Control")
|
||||
control := ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, c.GetControlType(), "Control Type")
|
||||
|
||||
value := ber.Encode(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, nil, "Control Value")
|
||||
seqs := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "SortKeyList")
|
||||
|
||||
for _, f := range c.SortKeys {
|
||||
@@ -968,9 +1021,11 @@ func (c *ControlServerSideSorting) Encode() *ber.Packet {
|
||||
seq.AppendChild(
|
||||
ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, f.AttributeType, "attributeType"),
|
||||
)
|
||||
seq.AppendChild(
|
||||
ber.NewString(ber.ClassContext, ber.TypePrimitive, 0, f.MatchingRule, "orderingRule"),
|
||||
)
|
||||
if f.MatchingRule != "" {
|
||||
seq.AppendChild(
|
||||
ber.NewString(ber.ClassContext, ber.TypePrimitive, 0, f.MatchingRule, "orderingRule"),
|
||||
)
|
||||
}
|
||||
if f.Reverse {
|
||||
seq.AppendChild(
|
||||
ber.NewBoolean(ber.ClassContext, ber.TypePrimitive, 1, f.Reverse, "reverseOrder"),
|
||||
@@ -980,7 +1035,7 @@ func (c *ControlServerSideSorting) Encode() *ber.Packet {
|
||||
seqs.AppendChild(seq)
|
||||
}
|
||||
|
||||
value.AppendChild(seqs)
|
||||
value := ber.Encode(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, string(seqs.Bytes()), "Control Value")
|
||||
|
||||
packet.AppendChild(control)
|
||||
packet.AppendChild(value)
|
||||
@@ -1060,6 +1115,8 @@ func NewControlServerSideSortingResult(pkt *ber.Packet) (*ControlServerSideSorti
|
||||
return nil, err
|
||||
}
|
||||
|
||||
control.Result = ControlServerSideSortingCode(codeInt)
|
||||
|
||||
return control, nil
|
||||
}
|
||||
|
||||
|
||||
+3
@@ -52,6 +52,9 @@ func (l *Conn) Del(delRequest *DelRequest) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(packet.Children) < 2 {
|
||||
return fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
|
||||
}
|
||||
if packet.Children[1].Tag == ApplicationDelResponse {
|
||||
err := GetLDAPError(packet)
|
||||
if err != nil {
|
||||
|
||||
+54
-7
@@ -1,14 +1,16 @@
|
||||
package ldap
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
ber "github.com/go-asn1-ber/asn1-ber"
|
||||
"sort"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
ber "github.com/go-asn1-ber/asn1-ber"
|
||||
)
|
||||
|
||||
// AttributeTypeAndValue represents an attributeTypeAndValue from https://tools.ietf.org/html/rfc4514
|
||||
@@ -94,9 +96,21 @@ func (d *DN) String() string {
|
||||
func stripLeadingAndTrailingSpaces(inVal string) string {
|
||||
noSpaces := strings.Trim(inVal, " ")
|
||||
|
||||
// Re-add the trailing space if it was an escaped space
|
||||
if len(noSpaces) > 0 && noSpaces[len(noSpaces)-1] == '\\' && inVal[len(inVal)-1] == ' ' {
|
||||
noSpaces = noSpaces + " "
|
||||
// Re-add the trailing space only if it was escaped. A trailing space is
|
||||
// escaped when it is preceded by an odd number of backslashes; an even
|
||||
// number leaves the space unescaped (each "\\" is a literal backslash), so
|
||||
// the space is insignificant and stays stripped. Counting only the final
|
||||
// backslash treated "\\ " (a literal backslash plus an insignificant
|
||||
// space) as an escaped space, keeping a spurious trailing space in the
|
||||
// decoded value.
|
||||
if len(noSpaces) > 0 && inVal[len(inVal)-1] == ' ' {
|
||||
backslashes := 0
|
||||
for i := len(noSpaces) - 1; i >= 0 && noSpaces[i] == '\\'; i-- {
|
||||
backslashes++
|
||||
}
|
||||
if backslashes%2 == 1 {
|
||||
noSpaces = noSpaces + " "
|
||||
}
|
||||
}
|
||||
|
||||
return noSpaces
|
||||
@@ -116,6 +130,16 @@ func decodeString(str string) (string, error) {
|
||||
// If the character is not an escape character, just add it to the
|
||||
// builder and continue
|
||||
if char != '\\' {
|
||||
// RFC 4514 section 2.4: these characters must appear escaped
|
||||
// (either as "\X" or as "\XX" hex) when present in an AttributeValue.
|
||||
// Reject the raw form here so that callers don't silently accept
|
||||
// input that violates the grammar.
|
||||
switch char {
|
||||
case '"', ';', '<', '>':
|
||||
return "", fmt.Errorf("got unescaped character: '%s'", string(char))
|
||||
case 0:
|
||||
return "", fmt.Errorf("got unescaped NULL character")
|
||||
}
|
||||
builder.WriteRune(char)
|
||||
continue
|
||||
}
|
||||
@@ -233,10 +257,18 @@ func decodeEncodedString(str string) (string, error) {
|
||||
return "", fmt.Errorf("failed to decode BER encoding: %w", err)
|
||||
}
|
||||
|
||||
packet, err := ber.DecodePacketErr(decoded)
|
||||
// RFC 4514 section 2.4: the value following '#' is the hex encoding of the
|
||||
// BER encoding of a single AttributeValue. Read exactly one element and
|
||||
// reject any leftover octets, otherwise bytes appended after the value are
|
||||
// silently dropped and two different DN strings decode to the same value.
|
||||
reader := bytes.NewBuffer(decoded)
|
||||
packet, err := ber.ReadPacket(reader)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to decode BER encoding: %w", err)
|
||||
}
|
||||
if reader.Len() != 0 {
|
||||
return "", errors.New("failed to decode BER encoding: trailing bytes after value")
|
||||
}
|
||||
|
||||
return packet.Data.String(), nil
|
||||
}
|
||||
@@ -352,10 +384,19 @@ func (r *RelativeDN) Equal(other *RelativeDN) bool {
|
||||
}
|
||||
|
||||
func (r *RelativeDN) hasAllAttributes(attrs []*AttributeTypeAndValue) bool {
|
||||
// Each candidate attribute must match a distinct attribute of the receiver.
|
||||
// Without consuming matches this is a set containment test, so a multi-valued
|
||||
// RDN that repeats an attributeTypeAndValue would compare equal to one that
|
||||
// repeats a different pair the same number of times.
|
||||
matched := make([]bool, len(r.Attributes))
|
||||
for _, attr := range attrs {
|
||||
found := false
|
||||
for _, myattr := range r.Attributes {
|
||||
for i, myattr := range r.Attributes {
|
||||
if matched[i] {
|
||||
continue
|
||||
}
|
||||
if myattr.Equal(attr) {
|
||||
matched[i] = true
|
||||
found = true
|
||||
break
|
||||
}
|
||||
@@ -415,10 +456,16 @@ func (r *RelativeDN) EqualFold(other *RelativeDN) bool {
|
||||
}
|
||||
|
||||
func (r *RelativeDN) hasAllAttributesFold(attrs []*AttributeTypeAndValue) bool {
|
||||
// See hasAllAttributes: matches are consumed so multiplicity is respected.
|
||||
matched := make([]bool, len(r.Attributes))
|
||||
for _, attr := range attrs {
|
||||
found := false
|
||||
for _, myattr := range r.Attributes {
|
||||
for i, myattr := range r.Attributes {
|
||||
if matched[i] {
|
||||
continue
|
||||
}
|
||||
if myattr.EqualFold(attr) {
|
||||
matched[i] = true
|
||||
found = true
|
||||
break
|
||||
}
|
||||
|
||||
+8
@@ -89,6 +89,14 @@ func (l *Conn) Extended(er *ExtendedRequest) (*ExtendedResponse, error) {
|
||||
}
|
||||
|
||||
for _, child := range extResp.Children {
|
||||
// responseName [10] and responseValue [11] are context-class and
|
||||
// optional. The preceding resultCode is a universal ENUMERATED whose
|
||||
// tag number (10) is the same as responseName, so a child must be
|
||||
// matched on its class as well, otherwise the resultCode is read as
|
||||
// the responseName whenever the server omits the latter.
|
||||
if child.ClassType != ber.ClassContext {
|
||||
continue
|
||||
}
|
||||
switch child.Tag {
|
||||
case ber.TagEnumerated:
|
||||
response.Name = child.Data.String()
|
||||
|
||||
+8
-8
@@ -131,7 +131,7 @@ func DecompileFilter(packet *ber.Packet) (_ string, err error) {
|
||||
buf.WriteString(childStr)
|
||||
|
||||
case FilterSubstrings:
|
||||
buf.WriteString(ber.DecodeString(packet.Children[0].Data.Bytes()))
|
||||
buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[0].Data.Bytes())))
|
||||
buf.WriteByte('=')
|
||||
for i, child := range packet.Children[1].Children {
|
||||
if i == 0 && child.Tag != FilterSubstringsInitial {
|
||||
@@ -143,22 +143,22 @@ func DecompileFilter(packet *ber.Packet) (_ string, err error) {
|
||||
}
|
||||
}
|
||||
case FilterEqualityMatch:
|
||||
buf.WriteString(ber.DecodeString(packet.Children[0].Data.Bytes()))
|
||||
buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[0].Data.Bytes())))
|
||||
buf.WriteByte('=')
|
||||
buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[1].Data.Bytes())))
|
||||
case FilterGreaterOrEqual:
|
||||
buf.WriteString(ber.DecodeString(packet.Children[0].Data.Bytes()))
|
||||
buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[0].Data.Bytes())))
|
||||
buf.WriteString(">=")
|
||||
buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[1].Data.Bytes())))
|
||||
case FilterLessOrEqual:
|
||||
buf.WriteString(ber.DecodeString(packet.Children[0].Data.Bytes()))
|
||||
buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[0].Data.Bytes())))
|
||||
buf.WriteString("<=")
|
||||
buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[1].Data.Bytes())))
|
||||
case FilterPresent:
|
||||
buf.WriteString(ber.DecodeString(packet.Data.Bytes()))
|
||||
buf.WriteString(EscapeFilter(ber.DecodeString(packet.Data.Bytes())))
|
||||
buf.WriteString("=*")
|
||||
case FilterApproxMatch:
|
||||
buf.WriteString(ber.DecodeString(packet.Children[0].Data.Bytes()))
|
||||
buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[0].Data.Bytes())))
|
||||
buf.WriteString("~=")
|
||||
buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[1].Data.Bytes())))
|
||||
case FilterExtensibleMatch:
|
||||
@@ -181,14 +181,14 @@ func DecompileFilter(packet *ber.Packet) (_ string, err error) {
|
||||
}
|
||||
|
||||
if len(attr) > 0 {
|
||||
buf.WriteString(attr)
|
||||
buf.WriteString(EscapeFilter(attr))
|
||||
}
|
||||
if dnAttributes {
|
||||
buf.WriteString(":dn")
|
||||
}
|
||||
if len(matchingRule) > 0 {
|
||||
buf.WriteString(":")
|
||||
buf.WriteString(matchingRule)
|
||||
buf.WriteString(EscapeFilter(matchingRule))
|
||||
}
|
||||
buf.WriteString(":=")
|
||||
buf.WriteString(EscapeFilter(value))
|
||||
|
||||
+3
@@ -89,6 +89,9 @@ func (l *Conn) ModifyDN(m *ModifyDNRequest) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(packet.Children) < 2 {
|
||||
return fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
|
||||
}
|
||||
if packet.Children[1].Tag == ApplicationModifyDNResponse {
|
||||
err := GetLDAPError(packet)
|
||||
if err != nil {
|
||||
|
||||
+7
@@ -121,6 +121,9 @@ func (l *Conn) Modify(modifyRequest *ModifyRequest) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(packet.Children) < 2 {
|
||||
return fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
|
||||
}
|
||||
if packet.Children[1].Tag == ApplicationModifyResponse {
|
||||
err := GetLDAPError(packet)
|
||||
if err != nil {
|
||||
@@ -159,6 +162,10 @@ func (l *Conn) ModifyWithResult(modifyRequest *ModifyRequest) (*ModifyResult, er
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(packet.Children) < 2 {
|
||||
return nil, fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
|
||||
}
|
||||
|
||||
switch packet.Children[1].Tag {
|
||||
case ApplicationModifyResponse:
|
||||
if err = GetLDAPError(packet); err != nil {
|
||||
|
||||
+7
-1
@@ -93,6 +93,9 @@ func (l *Conn) PasswordModify(passwordModifyRequest *PasswordModifyRequest) (*Pa
|
||||
|
||||
result := &PasswordModifyResult{}
|
||||
|
||||
if len(packet.Children) < 2 {
|
||||
return nil, fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
|
||||
}
|
||||
if packet.Children[1].Tag == ApplicationExtendedResponse {
|
||||
if err = GetLDAPError(packet); err != nil {
|
||||
result.Referral = getReferral(err, packet)
|
||||
@@ -106,7 +109,10 @@ func (l *Conn) PasswordModify(passwordModifyRequest *PasswordModifyRequest) (*Pa
|
||||
extendedResponse := packet.Children[1]
|
||||
for _, child := range extendedResponse.Children {
|
||||
if child.Tag == ber.TagEmbeddedPDV {
|
||||
passwordModifyResponseValue := ber.DecodePacket(child.Data.Bytes())
|
||||
passwordModifyResponseValue, err := ber.DecodePacketErr(child.Data.Bytes())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ldap: failed to decode PasswordModifyResponseValue: %s", err)
|
||||
}
|
||||
if len(passwordModifyResponseValue.Children) == 1 {
|
||||
if passwordModifyResponseValue.Children[0].Tag == ber.TagEOC {
|
||||
result.GeneratedPassword = ber.DecodeString(passwordModifyResponseValue.Children[0].Data.Bytes())
|
||||
|
||||
+8
@@ -101,6 +101,14 @@ func getReferral(err error, packet *ber.Packet) (referral string) {
|
||||
continue
|
||||
}
|
||||
|
||||
// A Referral is a SEQUENCE SIZE (1..MAX) OF uri, but a non-conforming or
|
||||
// malicious server can send an empty SEQUENCE. Skip it instead of indexing
|
||||
// child.Children[0], which would panic the goroutine that called Modify or
|
||||
// PasswordModify.
|
||||
if len(child.Children) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
if referral, ok = child.Children[0].Value.(string); ok {
|
||||
return referral
|
||||
}
|
||||
|
||||
+40
-16
@@ -66,12 +66,28 @@ func (r *searchResponse) Next() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// send enqueues a result on the result channel, giving up when ctx is
|
||||
// cancelled so an abandoned consumer cannot block the search goroutine
|
||||
// forever on a full buffer. It reports whether the result was handed off to
|
||||
// the channel; a true return does not mean the consumer received it. The
|
||||
// give-up is best-effort: if ctx is already cancelled but buffer space is
|
||||
// available, the result may still be enqueued. Callers that terminate the
|
||||
// stream regardless of the outcome may ignore the return value.
|
||||
func (r *searchResponse) send(ctx context.Context, res *SearchSingleResult) bool {
|
||||
select {
|
||||
case r.ch <- res:
|
||||
return true
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (r *searchResponse) start(ctx context.Context, searchRequest *SearchRequest) {
|
||||
go func() {
|
||||
defer func() {
|
||||
close(r.ch)
|
||||
if err := recover(); err != nil {
|
||||
r.conn.err = fmt.Errorf("ldap: recovered panic in searchResponse: %v", err)
|
||||
r.conn.setError(fmt.Errorf("ldap: recovered panic in searchResponse: %v", err))
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -84,14 +100,14 @@ func (r *searchResponse) start(ctx context.Context, searchRequest *SearchRequest
|
||||
// encode search request
|
||||
err := searchRequest.appendTo(packet)
|
||||
if err != nil {
|
||||
r.ch <- &SearchSingleResult{Error: err}
|
||||
r.send(ctx, &SearchSingleResult{Error: err})
|
||||
return
|
||||
}
|
||||
r.conn.Debug.PrintPacket(packet)
|
||||
|
||||
msgCtx, err := r.conn.sendMessage(packet)
|
||||
if err != nil {
|
||||
r.ch <- &SearchSingleResult{Error: err}
|
||||
r.send(ctx, &SearchSingleResult{Error: err})
|
||||
return
|
||||
}
|
||||
defer r.conn.finishMessage(msgCtx)
|
||||
@@ -106,19 +122,19 @@ func (r *searchResponse) start(ctx context.Context, searchRequest *SearchRequest
|
||||
case packetResponse, ok := <-msgCtx.responses:
|
||||
if !ok {
|
||||
err := NewError(ErrorNetwork, errors.New("ldap: response channel closed"))
|
||||
r.ch <- &SearchSingleResult{Error: err}
|
||||
r.send(ctx, &SearchSingleResult{Error: err})
|
||||
return
|
||||
}
|
||||
packet, err = packetResponse.ReadPacket()
|
||||
r.conn.Debug.Printf("%d: got response %p", msgCtx.id, packet)
|
||||
if err != nil {
|
||||
r.ch <- &SearchSingleResult{Error: err}
|
||||
r.send(ctx, &SearchSingleResult{Error: err})
|
||||
return
|
||||
}
|
||||
|
||||
if r.conn.Debug {
|
||||
if err := addLDAPDescriptions(packet); err != nil {
|
||||
r.ch <- &SearchSingleResult{Error: err}
|
||||
r.send(ctx, &SearchSingleResult{Error: err})
|
||||
return
|
||||
}
|
||||
ber.PrintPacket(packet)
|
||||
@@ -133,22 +149,26 @@ func (r *searchResponse) start(ctx context.Context, searchRequest *SearchRequest
|
||||
},
|
||||
}
|
||||
if len(packet.Children) != 3 {
|
||||
r.ch <- result
|
||||
if !r.send(ctx, result) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
decoded, err := DecodeControl(packet.Children[2].Children[0])
|
||||
if err != nil {
|
||||
werr := fmt.Errorf("failed to decode search result entry: %w", err)
|
||||
result.Error = werr
|
||||
r.ch <- result
|
||||
r.send(ctx, result)
|
||||
return
|
||||
}
|
||||
result.Controls = append(result.Controls, decoded)
|
||||
r.ch <- result
|
||||
if !r.send(ctx, result) {
|
||||
return
|
||||
}
|
||||
|
||||
case ApplicationSearchResultDone:
|
||||
if err := GetLDAPError(packet); err != nil {
|
||||
r.ch <- &SearchSingleResult{Error: err}
|
||||
r.send(ctx, &SearchSingleResult{Error: err})
|
||||
return
|
||||
}
|
||||
if len(packet.Children) == 3 {
|
||||
@@ -157,33 +177,37 @@ func (r *searchResponse) start(ctx context.Context, searchRequest *SearchRequest
|
||||
decodedChild, err := DecodeControl(child)
|
||||
if err != nil {
|
||||
werr := fmt.Errorf("failed to decode child control: %w", err)
|
||||
r.ch <- &SearchSingleResult{Error: werr}
|
||||
r.send(ctx, &SearchSingleResult{Error: werr})
|
||||
return
|
||||
}
|
||||
result.Controls = append(result.Controls, decodedChild)
|
||||
}
|
||||
r.ch <- result
|
||||
r.send(ctx, result)
|
||||
}
|
||||
foundSearchSingleResultDone = true
|
||||
|
||||
case ApplicationSearchResultReference:
|
||||
ref := packet.Children[1].Children[0].Value.(string)
|
||||
r.ch <- &SearchSingleResult{Referral: ref}
|
||||
if !r.send(ctx, &SearchSingleResult{Referral: ref}) {
|
||||
return
|
||||
}
|
||||
|
||||
case ApplicationIntermediateResponse:
|
||||
decoded, err := DecodeControl(packet.Children[1])
|
||||
if err != nil {
|
||||
werr := fmt.Errorf("failed to decode intermediate response: %w", err)
|
||||
r.ch <- &SearchSingleResult{Error: werr}
|
||||
r.send(ctx, &SearchSingleResult{Error: werr})
|
||||
return
|
||||
}
|
||||
result := &SearchSingleResult{}
|
||||
result.Controls = append(result.Controls, decoded)
|
||||
r.ch <- result
|
||||
if !r.send(ctx, result) {
|
||||
return
|
||||
}
|
||||
|
||||
default:
|
||||
err := fmt.Errorf("unknown tag: %d", packet.Children[1].Tag)
|
||||
r.ch <- &SearchSingleResult{Error: err}
|
||||
r.send(ctx, &SearchSingleResult{Error: err})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
+6
-2
@@ -624,7 +624,10 @@ func (l *Conn) Search(searchRequest *SearchRequest) (*SearchResult, error) {
|
||||
// SearchAsync performs a search request and returns all search results asynchronously.
|
||||
// This means you get all results until an error happens (or the search successfully finished),
|
||||
// e.g. for size / time limited requests all are received until the limit is reached.
|
||||
// To stop the search, call cancel function of the context.
|
||||
// To stop the search, call the cancel function of the context; Next may
|
||||
// still deliver a few results received before the cancellation took effect.
|
||||
// Cancellation is not reported as an error: Err returns nil, same as a
|
||||
// successfully completed search.
|
||||
func (l *Conn) SearchAsync(
|
||||
ctx context.Context, searchRequest *SearchRequest, bufferSize int) Response {
|
||||
r := newSearchResponse(l, bufferSize)
|
||||
@@ -635,7 +638,8 @@ func (l *Conn) SearchAsync(
|
||||
// Syncrepl is a short name for LDAP Sync Replication engine that works on the
|
||||
// consumer-side. This can perform a persistent search and returns an entry
|
||||
// when the entry is updated on the server side.
|
||||
// To stop the search, call cancel function of the context.
|
||||
// To stop the search, call the cancel function of the context; cancellation
|
||||
// is not reported as an error, Err returns nil.
|
||||
func (l *Conn) Syncrepl(
|
||||
ctx context.Context, searchRequest *SearchRequest, bufferSize int,
|
||||
mode ControlSyncRequestMode, cookie []byte, reloadHint bool,
|
||||
|
||||
+8
-1
@@ -24,11 +24,18 @@ func (l *Conn) Unbind() error {
|
||||
return ErrConnUnbound
|
||||
}
|
||||
|
||||
_, err := l.doRequest(unbindRequest{})
|
||||
msgCtx, err := l.doRequest(unbindRequest{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Finish the message context so its done channel is closed. Without
|
||||
// this, a server-initiated disconnect racing with Close can deadlock:
|
||||
// processMessages cleanup tries to deliver closeErr to the orphaned
|
||||
// context via sendResponse, which blocks forever on the unclosed done
|
||||
// channel, preventing chanConfirm from being signalled.
|
||||
l.finishMessage(msgCtx)
|
||||
|
||||
// Sending an unbindRequest will make the connection unusable.
|
||||
// Pending requests will fail with:
|
||||
// LDAP Result Code 200 "Network Error": ldap: response channel closed
|
||||
|
||||
+7
-1
@@ -19,5 +19,11 @@ func (l *Conn) WhoAmI(controls []Control) (*WhoAmIResult, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &WhoAmIResult{AuthzID: resp.Value.Data.String()}, nil
|
||||
// responseValue is OPTIONAL (RFC 4532); Extended leaves Value nil when the
|
||||
// server omits it. Guard the dereference and report an empty authzId.
|
||||
result := &WhoAmIResult{}
|
||||
if resp.Value != nil {
|
||||
result.AuthzID = resp.Value.Data.String()
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
+12
@@ -27,6 +27,18 @@ Use the links above for more information on each.
|
||||
|
||||
# changelog
|
||||
|
||||
* Jul 1st, 2026 [1.19.0](https://github.com/klauspost/compress/releases/tag/v1.19.0)
|
||||
* zstd: Add true concurrent stream encodingin https://github.com/klauspost/compress/pull/1136
|
||||
* zstd: arm64 decoder asm by @lizthegrey in https://github.com/klauspost/compress/pull/1160
|
||||
* flate: Add inflate checkpoints in https://github.com/klauspost/compress/pull/1154
|
||||
* zstd: avoid unused BuildDict encoder allocation by @snissn in https://github.com/klauspost/compress/pull/1147
|
||||
* snappy/s2: Limit length of varint in `decodedLen` by @eustas in https://github.com/klauspost/compress/pull/1148
|
||||
* gzhttp: match qvalue parameter case-insensitively (RFC 7231) by @z9z in https://github.com/klauspost/compress/pull/1149
|
||||
* zip: add NameDecoder callback for legacy encoding rewrite by @SAY-5 in https://github.com/klauspost/compress/pull/1150
|
||||
* huff0: Allow building tables from histogram in https://github.com/klauspost/compress/pull/1155
|
||||
* huff0: Allow building table from oversized histogram in https://github.com/klauspost/compress/pull/1156
|
||||
* s2sx: Clean symlink targets in https://github.com/klauspost/compress/pull/1163
|
||||
|
||||
* Feb 9th, 2026 [1.18.4](https://github.com/klauspost/compress/releases/tag/v1.18.4)
|
||||
* gzhttp: Add zstandard to server handler wrapper https://github.com/klauspost/compress/pull/1121
|
||||
* zstd: Add ResetWithOptions to encoder/decoder https://github.com/klauspost/compress/pull/1122
|
||||
|
||||
+21
-3
@@ -28,9 +28,10 @@ type dictDecoder struct {
|
||||
hist []byte // Sliding window history
|
||||
|
||||
// Invariant: 0 <= rdPos <= wrPos <= len(hist)
|
||||
wrPos int // Current output position in buffer
|
||||
rdPos int // Have emitted hist[:rdPos] already
|
||||
full bool // Has a full window length been written yet?
|
||||
wrPos int // Current output position in buffer
|
||||
rdPos int // Have emitted hist[:rdPos] already
|
||||
flushed int64 // Total bytes returned by readFlush since init
|
||||
full bool // Has a full window length been written yet?
|
||||
}
|
||||
|
||||
// init initializes dictDecoder to have a sliding window dictionary of the given
|
||||
@@ -167,11 +168,22 @@ loop:
|
||||
return dstPos - dstBase
|
||||
}
|
||||
|
||||
// appendWindow appends the current sliding window (up to len(hist) most recent
|
||||
// bytes, oldest first) to dst.
|
||||
func (dd *dictDecoder) appendWindow(dst []byte) []byte {
|
||||
if dd.full {
|
||||
dst = append(dst, dd.hist[dd.wrPos:]...)
|
||||
return append(dst, dd.hist[:dd.wrPos]...)
|
||||
}
|
||||
return append(dst, dd.hist[:dd.wrPos]...)
|
||||
}
|
||||
|
||||
// readFlush returns a slice of the historical buffer that is ready to be
|
||||
// emitted to the user. The data returned by readFlush must be fully consumed
|
||||
// before calling any other dictDecoder methods.
|
||||
func (dd *dictDecoder) readFlush() []byte {
|
||||
toRead := dd.hist[dd.rdPos:dd.wrPos]
|
||||
dd.flushed += int64(len(toRead))
|
||||
dd.rdPos = dd.wrPos
|
||||
if dd.wrPos == len(dd.hist) {
|
||||
dd.wrPos, dd.rdPos = 0, 0
|
||||
@@ -179,3 +191,9 @@ func (dd *dictDecoder) readFlush() []byte {
|
||||
}
|
||||
return toRead
|
||||
}
|
||||
|
||||
// decoded reports the total number of bytes written into the dictionary since
|
||||
// init (i.e. excluding any preset dict bytes).
|
||||
func (dd *dictDecoder) decoded() int64 {
|
||||
return dd.flushed + int64(dd.wrPos-dd.rdPos)
|
||||
}
|
||||
+92
@@ -342,6 +342,11 @@ type decompressor struct {
|
||||
final bool
|
||||
|
||||
flushMode flushMode
|
||||
cb func(InflateCheckpoint)
|
||||
cp InflateCheckpoint
|
||||
hasCP bool // WithResumeFrom was supplied
|
||||
uncOffset int64 // baseline uncompressed offset (from a resume checkpoint)
|
||||
cpBuf []byte
|
||||
}
|
||||
|
||||
func (f *decompressor) nextBlock() {
|
||||
@@ -676,6 +681,18 @@ func (f *decompressor) finishBlock() {
|
||||
f.toRead = f.dict.readFlush()
|
||||
}
|
||||
|
||||
if f.cb != nil {
|
||||
bitPos := f.roffset*8 - int64(f.nb)
|
||||
f.cpBuf = f.dict.appendWindow(f.cpBuf[:0])
|
||||
f.cb(InflateCheckpoint{
|
||||
UncompressedOffset: f.uncOffset + f.dict.decoded(),
|
||||
CompressedOffset: bitPos / 8,
|
||||
Final: f.final,
|
||||
BitOffset: uint8(bitPos & 7),
|
||||
Window: f.cpBuf,
|
||||
})
|
||||
}
|
||||
|
||||
f.step = nextBlock
|
||||
}
|
||||
|
||||
@@ -806,6 +823,45 @@ func (f *decompressor) Reset(r io.Reader, dict []byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ResetCP will adjust the input to the provided checkpoint.
|
||||
// It is assumed the input stream is forwarded to cp.CompressedOffset.
|
||||
func (f *decompressor) ResetCP(r io.Reader, cp InflateCheckpoint) error {
|
||||
*f = decompressor{
|
||||
r: makeReader(r),
|
||||
bits: f.bits,
|
||||
codebits: f.codebits,
|
||||
h1: f.h1,
|
||||
h2: f.h2,
|
||||
dict: f.dict,
|
||||
step: nextBlock,
|
||||
cpBuf: f.cpBuf,
|
||||
}
|
||||
return f.applyCP(cp)
|
||||
}
|
||||
|
||||
// applyCP seeds the decompressor state from a resume checkpoint:
|
||||
// loads the sliding window, sets the absolute compressed/uncompressed
|
||||
// offsets, and skips cp.BitOffset bits into the first input byte so
|
||||
// the next decode aligns with the start of a deflate block.
|
||||
func (f *decompressor) applyCP(cp InflateCheckpoint) error {
|
||||
f.dict.init(maxMatchOffset, cp.Window)
|
||||
f.roffset = cp.CompressedOffset
|
||||
f.uncOffset = cp.UncompressedOffset
|
||||
f.final = cp.Final
|
||||
f.b = 0
|
||||
f.nb = 0
|
||||
if cp.BitOffset > 0 {
|
||||
c, err := f.r.ReadByte()
|
||||
if err != nil {
|
||||
return noEOF(err)
|
||||
}
|
||||
f.roffset++
|
||||
f.b = uint32(c) >> cp.BitOffset
|
||||
f.nb = 8 - uint(cp.BitOffset)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type ReaderOpt func(*decompressor)
|
||||
|
||||
// WithPartialBlock tells decompressor to return after each block,
|
||||
@@ -823,6 +879,36 @@ func WithDict(dict []byte) ReaderOpt {
|
||||
}
|
||||
}
|
||||
|
||||
// InflateCheckpoint provides a resumable checkpoint for inflate.
|
||||
type InflateCheckpoint struct {
|
||||
UncompressedOffset int64 // Byte offset in the decompressed stream
|
||||
CompressedOffset int64 // Byte offset in the compressed stream
|
||||
Final bool // True if this is the final block
|
||||
BitOffset uint8 // 0-7 bits
|
||||
Window []byte // 32KB sliding window dictionary
|
||||
}
|
||||
|
||||
// WithEobCallback will call the provided function after each block
|
||||
// with the current gzip checkpoint.
|
||||
// After returning the provided window can no longer be referenced.
|
||||
// The callback will not be triggered after a block is marked "final".
|
||||
// The callback is not retained after Reset.
|
||||
func WithEobCallback(cb func(InflateCheckpoint)) ReaderOpt {
|
||||
return func(f *decompressor) {
|
||||
f.cb = cb
|
||||
}
|
||||
}
|
||||
|
||||
// WithResumeFrom will adjust the input to the provided checkpoint.
|
||||
// It is assumed the input stream is forwarded to the provided offset.
|
||||
// The checkpoint is removed when Reset is called.
|
||||
func WithResumeFrom(cp InflateCheckpoint) ReaderOpt {
|
||||
return func(f *decompressor) {
|
||||
f.cp = cp
|
||||
f.hasCP = true
|
||||
}
|
||||
}
|
||||
|
||||
// NewReaderOpts returns new reader with provided options
|
||||
func NewReaderOpts(r io.Reader, opts ...ReaderOpt) io.ReadCloser {
|
||||
fixedHuffmanDecoderInit()
|
||||
@@ -838,6 +924,12 @@ func NewReaderOpts(r io.Reader, opts ...ReaderOpt) io.ReadCloser {
|
||||
opt(&f)
|
||||
}
|
||||
|
||||
if f.hasCP {
|
||||
if err := f.applyCP(f.cp); err != nil {
|
||||
f.err = err
|
||||
}
|
||||
}
|
||||
|
||||
return &f
|
||||
}
|
||||
|
||||
|
||||
+85
-31
@@ -10,6 +10,15 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
func peekBufio(fr *bufio.Reader) ([]byte, error) {
|
||||
if fr.Buffered() == 0 {
|
||||
if _, err := fr.Peek(1); err != nil && fr.Buffered() == 0 {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return fr.Peek(fr.Buffered())
|
||||
}
|
||||
|
||||
// Decode a single Huffman block from f.
|
||||
// hl and hd are the Huffman states for the lit/length values
|
||||
// and the distance values, respectively. If hd == nil, using the
|
||||
@@ -527,6 +536,8 @@ func (f *decompressor) huffmanBufioReader() {
|
||||
// but is smart enough to keep local variables in registers, so use nb and b,
|
||||
// inline call to moreBits and reassign b,nb back to f on return.
|
||||
fnb, fb, dict := f.nb, f.b, &f.dict
|
||||
pbuf, _ := fr.Peek(fr.Buffered())
|
||||
pos := 0
|
||||
|
||||
switch f.stepState {
|
||||
case stateInit:
|
||||
@@ -548,12 +559,19 @@ readLiteral:
|
||||
n := uint(f.hl.maxRead)
|
||||
for {
|
||||
for fnb < n {
|
||||
c, err := fr.ReadByte()
|
||||
if err != nil {
|
||||
f.b, f.nb = fb, fnb
|
||||
f.err = noEOF(err)
|
||||
return
|
||||
if pos >= len(pbuf) {
|
||||
fr.Discard(pos)
|
||||
var err error
|
||||
pbuf, err = peekBufio(fr)
|
||||
pos = 0
|
||||
if len(pbuf) == 0 {
|
||||
f.b, f.nb = fb, fnb
|
||||
f.err = noEOF(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
c := pbuf[pos]
|
||||
pos++
|
||||
f.roffset++
|
||||
fb |= uint32(c) << (fnb & regSizeMaskUint32)
|
||||
fnb += 8
|
||||
@@ -566,6 +584,7 @@ readLiteral:
|
||||
}
|
||||
if n <= fnb {
|
||||
if n == 0 {
|
||||
fr.Discard(pos)
|
||||
f.b, f.nb = fb, fnb
|
||||
if debugDecode {
|
||||
fmt.Println("huffsym: n==0")
|
||||
@@ -586,6 +605,7 @@ readLiteral:
|
||||
case v < 256:
|
||||
dict.writeByte(byte(v))
|
||||
if dict.availWrite() == 0 {
|
||||
fr.Discard(pos)
|
||||
f.toRead = dict.readFlush()
|
||||
f.step = huffmanBufioReader
|
||||
f.stepState = stateInit
|
||||
@@ -594,6 +614,7 @@ readLiteral:
|
||||
}
|
||||
goto readLiteral
|
||||
case v == 256:
|
||||
fr.Discard(pos)
|
||||
f.b, f.nb = fb, fnb
|
||||
f.finishBlock()
|
||||
return
|
||||
@@ -605,15 +626,22 @@ readLiteral:
|
||||
length = int(val.length) + 3
|
||||
n := uint(val.extra)
|
||||
for fnb < n {
|
||||
c, err := fr.ReadByte()
|
||||
if err != nil {
|
||||
f.b, f.nb = fb, fnb
|
||||
if debugDecode {
|
||||
fmt.Println("morebits n>0:", err)
|
||||
if pos >= len(pbuf) {
|
||||
fr.Discard(pos)
|
||||
var err error
|
||||
pbuf, err = peekBufio(fr)
|
||||
pos = 0
|
||||
if len(pbuf) == 0 {
|
||||
f.b, f.nb = fb, fnb
|
||||
if debugDecode {
|
||||
fmt.Println("morebits n>0:", err)
|
||||
}
|
||||
f.err = err
|
||||
return
|
||||
}
|
||||
f.err = err
|
||||
return
|
||||
}
|
||||
c := pbuf[pos]
|
||||
pos++
|
||||
f.roffset++
|
||||
fb |= uint32(c) << (fnb & regSizeMaskUint32)
|
||||
fnb += 8
|
||||
@@ -622,6 +650,7 @@ readLiteral:
|
||||
fb >>= n & regSizeMaskUint32
|
||||
fnb -= n
|
||||
default:
|
||||
fr.Discard(pos)
|
||||
if debugDecode {
|
||||
fmt.Println(v, ">= maxNumLit")
|
||||
}
|
||||
@@ -633,15 +662,22 @@ readLiteral:
|
||||
var dist uint32
|
||||
if f.hd == nil {
|
||||
for fnb < 5 {
|
||||
c, err := fr.ReadByte()
|
||||
if err != nil {
|
||||
f.b, f.nb = fb, fnb
|
||||
if debugDecode {
|
||||
fmt.Println("morebits f.nb<5:", err)
|
||||
if pos >= len(pbuf) {
|
||||
fr.Discard(pos)
|
||||
var err error
|
||||
pbuf, err = peekBufio(fr)
|
||||
pos = 0
|
||||
if len(pbuf) == 0 {
|
||||
f.b, f.nb = fb, fnb
|
||||
if debugDecode {
|
||||
fmt.Println("morebits f.nb<5:", err)
|
||||
}
|
||||
f.err = err
|
||||
return
|
||||
}
|
||||
f.err = err
|
||||
return
|
||||
}
|
||||
c := pbuf[pos]
|
||||
pos++
|
||||
f.roffset++
|
||||
fb |= uint32(c) << (fnb & regSizeMaskUint32)
|
||||
fnb += 8
|
||||
@@ -660,12 +696,19 @@ readLiteral:
|
||||
// inline call to moreBits and reassign b,nb back to f on return.
|
||||
for {
|
||||
for fnb < n {
|
||||
c, err := fr.ReadByte()
|
||||
if err != nil {
|
||||
f.b, f.nb = fb, fnb
|
||||
f.err = noEOF(err)
|
||||
return
|
||||
if pos >= len(pbuf) {
|
||||
fr.Discard(pos)
|
||||
var err error
|
||||
pbuf, err = peekBufio(fr)
|
||||
pos = 0
|
||||
if len(pbuf) == 0 {
|
||||
f.b, f.nb = fb, fnb
|
||||
f.err = noEOF(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
c := pbuf[pos]
|
||||
pos++
|
||||
f.roffset++
|
||||
fb |= uint32(c) << (fnb & regSizeMaskUint32)
|
||||
fnb += 8
|
||||
@@ -678,6 +721,7 @@ readLiteral:
|
||||
}
|
||||
if n <= fnb {
|
||||
if n == 0 {
|
||||
fr.Discard(pos)
|
||||
f.b, f.nb = fb, fnb
|
||||
if debugDecode {
|
||||
fmt.Println("huffsym: n==0")
|
||||
@@ -701,15 +745,22 @@ readLiteral:
|
||||
// have 1 bit in bottom of dist, need nb more.
|
||||
extra := (dist & 1) << (nb & regSizeMaskUint32)
|
||||
for fnb < nb {
|
||||
c, err := fr.ReadByte()
|
||||
if err != nil {
|
||||
f.b, f.nb = fb, fnb
|
||||
if debugDecode {
|
||||
fmt.Println("morebits f.nb<nb:", err)
|
||||
if pos >= len(pbuf) {
|
||||
fr.Discard(pos)
|
||||
var err error
|
||||
pbuf, err = peekBufio(fr)
|
||||
pos = 0
|
||||
if len(pbuf) == 0 {
|
||||
f.b, f.nb = fb, fnb
|
||||
if debugDecode {
|
||||
fmt.Println("morebits f.nb<nb:", err)
|
||||
}
|
||||
f.err = err
|
||||
return
|
||||
}
|
||||
f.err = err
|
||||
return
|
||||
}
|
||||
c := pbuf[pos]
|
||||
pos++
|
||||
f.roffset++
|
||||
fb |= uint32(c) << (fnb & regSizeMaskUint32)
|
||||
fnb += 8
|
||||
@@ -720,6 +771,7 @@ readLiteral:
|
||||
dist = 1<<((nb+1)®SizeMaskUint32) + 1 + extra
|
||||
// slower: dist = bitMask32[nb+1] + 2 + extra
|
||||
default:
|
||||
fr.Discard(pos)
|
||||
f.b, f.nb = fb, fnb
|
||||
if debugDecode {
|
||||
fmt.Println("dist too big:", dist, maxNumDist)
|
||||
@@ -730,6 +782,7 @@ readLiteral:
|
||||
|
||||
// No check on length; encoding can be prescient.
|
||||
if dist > uint32(dict.histSize()) {
|
||||
fr.Discard(pos)
|
||||
f.b, f.nb = fb, fnb
|
||||
if debugDecode {
|
||||
fmt.Println("dist > dict.histSize():", dist, dict.histSize())
|
||||
@@ -752,6 +805,7 @@ copyHistory:
|
||||
f.copyLen -= cnt
|
||||
|
||||
if dict.availWrite() == 0 || f.copyLen > 0 {
|
||||
fr.Discard(pos)
|
||||
f.toRead = dict.readFlush()
|
||||
f.step = huffmanBufioReader // We need to continue this work
|
||||
f.stepState = stateDict
|
||||
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
package huff0
|
||||
|
||||
import "errors"
|
||||
|
||||
// BuildCTable builds a Huffman compression table from a precomputed symbol
|
||||
// histogram and installs it as the previous (reuse) table on s.
|
||||
//
|
||||
// After this call:
|
||||
// - EstimateSize/CanUseTable can probe the table against other histograms.
|
||||
// - Compress1X/Compress4X with Reuse = ReusePolicyMust will encode without
|
||||
// emitting a new table header.
|
||||
// - TransferCTable can hand the table to a sibling Scratch.
|
||||
//
|
||||
// count[i] is the number of occurrences of symbol i. The histogram must have
|
||||
// at least 2 distinct non-zero symbols; ErrUseRLE is returned for a single
|
||||
// symbol and an error is returned for an empty histogram.
|
||||
func (s *Scratch) BuildCTable(count *[256]uint32) error {
|
||||
if s == nil {
|
||||
return errors.New("huff0: BuildCTable on nil Scratch")
|
||||
}
|
||||
if count == nil {
|
||||
return errors.New("huff0: nil count passed to BuildCTable")
|
||||
}
|
||||
var err error
|
||||
s, err = s.prepare(nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.count = *count
|
||||
var total, maxCount int
|
||||
var symLen uint16
|
||||
for i, v := range s.count {
|
||||
total += int(v)
|
||||
if int(v) > maxCount {
|
||||
maxCount = int(v)
|
||||
}
|
||||
if v != 0 {
|
||||
symLen = uint16(i) + 1
|
||||
}
|
||||
}
|
||||
if total == 0 {
|
||||
return errors.New("huff0: empty histogram")
|
||||
}
|
||||
if symLen < 2 || maxCount == total {
|
||||
return ErrUseRLE
|
||||
}
|
||||
// huff0's internal rank table assumes total ≤ BlockSizeMax (it uses
|
||||
// highBit32(count+1) + 1 as a rank index into a fixed-size array).
|
||||
// Histograms summed across multiple blocks can exceed that; scale the
|
||||
// counts down preserving the distribution. Non-zero entries round up so
|
||||
// rare symbols stay representable.
|
||||
if total > BlockSizeMax {
|
||||
shift := uint(0)
|
||||
for total>>shift > BlockSizeMax {
|
||||
shift++
|
||||
}
|
||||
round := uint32(1<<shift) - 1
|
||||
var newTotal, newMax int
|
||||
for i, v := range s.count {
|
||||
if v == 0 {
|
||||
continue
|
||||
}
|
||||
scaled := (v + round) >> shift
|
||||
if scaled == 0 {
|
||||
scaled = 1
|
||||
}
|
||||
s.count[i] = scaled
|
||||
newTotal += int(scaled)
|
||||
if int(scaled) > newMax {
|
||||
newMax = int(scaled)
|
||||
}
|
||||
}
|
||||
total = newTotal
|
||||
maxCount = newMax
|
||||
if maxCount == total {
|
||||
return ErrUseRLE
|
||||
}
|
||||
}
|
||||
s.symbolLen = symLen
|
||||
s.maxCount = maxCount
|
||||
s.srcLen = total
|
||||
if err := s.buildCTable(); err != nil {
|
||||
return err
|
||||
}
|
||||
if cap(s.prevTable) < len(s.cTable) {
|
||||
s.prevTable = make(cTable, 0, maxSymbolValue+1)
|
||||
}
|
||||
s.prevTable = s.prevTable[:len(s.cTable)]
|
||||
copy(s.prevTable, s.cTable)
|
||||
s.prevTableLog = s.actualTableLog
|
||||
// Force the next Compress* to recount from real input.
|
||||
s.clearCount = true
|
||||
s.maxCount = 0
|
||||
return nil
|
||||
}
|
||||
|
||||
// EstimateSize returns an estimated compressed payload size in bytes for the
|
||||
// supplied histogram using the table currently stored in prevTable. It returns
|
||||
// -1 when the table cannot encode every non-zero symbol of hist (i.e. when
|
||||
// CanUseTable would return false). The estimate excludes the table header.
|
||||
func (s *Scratch) EstimateSize(hist *[256]uint32) int {
|
||||
if s == nil || hist == nil || len(s.prevTable) == 0 {
|
||||
return -1
|
||||
}
|
||||
pt := s.prevTable
|
||||
nbBits := uint32(7)
|
||||
for i, v := range hist {
|
||||
if v == 0 {
|
||||
continue
|
||||
}
|
||||
if i >= len(pt) || pt[i].nBits == 0 {
|
||||
return -1
|
||||
}
|
||||
nbBits += uint32(pt[i].nBits) * v
|
||||
}
|
||||
return int(nbBits >> 3)
|
||||
}
|
||||
|
||||
// CanUseTable reports whether the table in prevTable can encode every
|
||||
// non-zero symbol present in hist.
|
||||
func (s *Scratch) CanUseTable(hist *[256]uint32) bool {
|
||||
if s == nil || hist == nil || len(s.prevTable) == 0 {
|
||||
return false
|
||||
}
|
||||
pt := s.prevTable
|
||||
for i, v := range hist {
|
||||
if v == 0 {
|
||||
continue
|
||||
}
|
||||
if i >= len(pt) || pt[i].nBits == 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// AppendTable serializes the table currently stored in prevTable (e.g. as
|
||||
// installed by BuildCTable or carried over from a previous Compress call)
|
||||
// into a self-delimiting zstd-style header and appends it to dst. The
|
||||
// returned slice can be parsed back by ReadTable.
|
||||
func (s *Scratch) AppendTable(dst []byte) ([]byte, error) {
|
||||
if s == nil || len(s.prevTable) == 0 {
|
||||
return dst, errors.New("huff0: AppendTable with empty table")
|
||||
}
|
||||
// cTable.write reads s.actualTableLog, s.symbolLen, s.huffWeight, s.fse
|
||||
// and writes into s.Out. Save/restore Out so we don't disturb in-flight
|
||||
// compression buffers.
|
||||
saveOut := s.Out
|
||||
saveTL := s.actualTableLog
|
||||
saveSL := s.symbolLen
|
||||
if s.fse == nil {
|
||||
// Lazily init in case AppendTable is called on a fresh Scratch.
|
||||
if _, err := s.prepare(nil); err != nil {
|
||||
return dst, err
|
||||
}
|
||||
saveOut = s.Out
|
||||
}
|
||||
s.Out = s.Out[:0]
|
||||
s.actualTableLog = s.prevTableLog
|
||||
s.symbolLen = uint16(len(s.prevTable))
|
||||
if err := s.prevTable.write(s); err != nil {
|
||||
s.Out, s.actualTableLog, s.symbolLen = saveOut, saveTL, saveSL
|
||||
return dst, err
|
||||
}
|
||||
dst = append(dst, s.Out...)
|
||||
s.Out, s.actualTableLog, s.symbolLen = saveOut, saveTL, saveSL
|
||||
return dst, nil
|
||||
}
|
||||
+1
-1
@@ -31,7 +31,7 @@ func DecodedLen(src []byte) (int, error) {
|
||||
// that the length header occupied.
|
||||
func decodedLen(src []byte) (blockLen, headerLen int, err error) {
|
||||
v, n := binary.Uvarint(src)
|
||||
if n <= 0 || v > 0xffffffff {
|
||||
if n <= 0 || n > 5 || v > 0xffffffff {
|
||||
return 0, 0, ErrCorrupt
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ func DecodedLen(src []byte) (int, error) {
|
||||
// that the length header occupied.
|
||||
func decodedLen(src []byte) (blockLen, headerLen int, err error) {
|
||||
v, n := binary.Uvarint(src)
|
||||
if n <= 0 || v > 0xffffffff {
|
||||
if n <= 0 || n > 5 || v > 0xffffffff {
|
||||
return 0, 0, ErrCorrupt
|
||||
}
|
||||
|
||||
|
||||
+4
-2
@@ -56,10 +56,12 @@ func NewDict(dict []byte) *Dict {
|
||||
if len(dict) < MinDictSize || len(dict) > MaxDictSize {
|
||||
return nil
|
||||
}
|
||||
d.repeat = int(r)
|
||||
if d.repeat > len(dict) {
|
||||
// Compare as uint64: int(r) would wrap negative for r > MaxInt64,
|
||||
// slipping past the bounds check and causing an OOB read in encode.
|
||||
if r > uint64(len(dict)) {
|
||||
return nil
|
||||
}
|
||||
d.repeat = int(r)
|
||||
return &d
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -981,7 +981,7 @@ searchDict:
|
||||
cv = load64(src, s)
|
||||
continue
|
||||
}
|
||||
} else if uint32(cv>>(checkRep*8)) == load32(src, s-repeat+checkRep) {
|
||||
} else if repeat > 0 && uint32(cv>>(checkRep*8)) == load32(src, s-repeat+checkRep) {
|
||||
base := s + checkRep
|
||||
// Extend back
|
||||
for i := base - repeat; base > nextEmit && i > 0 && src[i-1] == src[base-1]; {
|
||||
|
||||
+3
-3
@@ -25,7 +25,7 @@ type betterTables struct {
|
||||
sTable [betterShortTableSize]uint32
|
||||
}
|
||||
|
||||
var betterTablePool = sync.Pool{New: func() interface{} { return &betterTables{} }}
|
||||
var betterTablePool = sync.Pool{New: func() any { return &betterTables{} }}
|
||||
|
||||
// betterSnappyTables holds better-snappy compression hash tables.
|
||||
type betterSnappyTables struct {
|
||||
@@ -33,7 +33,7 @@ type betterSnappyTables struct {
|
||||
sTable [betterShortTableSize]uint32
|
||||
}
|
||||
|
||||
var betterSnappyTablePool = sync.Pool{New: func() interface{} { return &betterSnappyTables{} }}
|
||||
var betterSnappyTablePool = sync.Pool{New: func() any { return &betterSnappyTables{} }}
|
||||
|
||||
// bestTables holds best compression hash tables.
|
||||
type bestTables struct {
|
||||
@@ -41,7 +41,7 @@ type bestTables struct {
|
||||
sTable [bestShortTableSize]uint64
|
||||
}
|
||||
|
||||
var bestTablePool = sync.Pool{New: func() interface{} { return &bestTables{} }}
|
||||
var bestTablePool = sync.Pool{New: func() any { return &bestTables{} }}
|
||||
|
||||
// getBetterTables gets a zeroed betterTables from the pool.
|
||||
func getBetterTables() *betterTables {
|
||||
|
||||
+12
-7
@@ -216,13 +216,18 @@ func (r *Reader) skippable(tmp []byte, n int, allowEOF bool, id uint8) (ok bool)
|
||||
return r.err == nil
|
||||
}
|
||||
if rs, ok := r.r.(io.ReadSeeker); ok {
|
||||
_, err := rs.Seek(int64(n), io.SeekCurrent)
|
||||
if err == nil {
|
||||
return true
|
||||
}
|
||||
if err == io.ErrUnexpectedEOF || (r.err == io.EOF && !allowEOF) {
|
||||
r.err = ErrCorrupt
|
||||
return false
|
||||
if cur, err := rs.Seek(0, io.SeekCurrent); err == nil {
|
||||
if end, err := rs.Seek(0, io.SeekEnd); err == nil {
|
||||
if cur+int64(n) <= end {
|
||||
if _, err := rs.Seek(cur+int64(n), io.SeekStart); err == nil {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if _, err := rs.Seek(cur, io.SeekStart); err != nil {
|
||||
r.err = ErrCorrupt
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for n > 0 {
|
||||
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
// Copyright 2011 The Snappy-Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package snappy
|
||||
|
||||
import "encoding/binary"
|
||||
|
||||
// DecodeStrict returns the decoded form of src, like Decode.
|
||||
//
|
||||
// Unlike Decode, which delegates to the s2 decoder and accepts the s2
|
||||
// "repeat last offset" extension (a copy whose encoded offset is 0),
|
||||
// DecodeStrict uses a strict standard-Snappy block decoder. Offset 0 is not
|
||||
// valid in the standard Snappy block format, so such a copy is rejected with
|
||||
// ErrCorrupt. This makes DecodeStrict match github.com/golang/snappy and the
|
||||
// C++ reference decoder, at the cost of being slower than Decode.
|
||||
//
|
||||
// The returned slice may be a sub-slice of dst if dst was large enough to
|
||||
// hold the entire decoded block. Otherwise, a newly allocated slice will be
|
||||
// returned.
|
||||
//
|
||||
// The dst and src must not overlap. It is valid to pass a nil dst.
|
||||
//
|
||||
// DecodeStrict handles the Snappy block format, not the Snappy stream format.
|
||||
func DecodeStrict(dst, src []byte) ([]byte, error) {
|
||||
v, n := binary.Uvarint(src)
|
||||
if n <= 0 || n > 5 || v > 0xffffffff {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
const wordSize = 32 << (^uint(0) >> 32 & 1)
|
||||
if wordSize == 32 && v > 0x7fffffff {
|
||||
return nil, ErrTooLarge
|
||||
}
|
||||
dLen := int(v)
|
||||
if dLen <= cap(dst) {
|
||||
dst = dst[:dLen]
|
||||
} else {
|
||||
dst = make([]byte, dLen)
|
||||
}
|
||||
if decodeStrict(dst, src[n:]) != 0 {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
return dst, nil
|
||||
}
|
||||
|
||||
func decodeStrict(dst, src []byte) int {
|
||||
var d, s, offset, length int
|
||||
for s < len(src) {
|
||||
switch src[s] & 0x03 {
|
||||
case 0x00:
|
||||
x := uint32(src[s] >> 2)
|
||||
switch {
|
||||
case x < 60:
|
||||
s++
|
||||
case x == 60:
|
||||
s += 2
|
||||
if uint(s) > uint(len(src)) {
|
||||
return 1
|
||||
}
|
||||
x = uint32(src[s-1])
|
||||
case x == 61:
|
||||
s += 3
|
||||
if uint(s) > uint(len(src)) {
|
||||
return 1
|
||||
}
|
||||
x = uint32(src[s-2]) | uint32(src[s-1])<<8
|
||||
case x == 62:
|
||||
s += 4
|
||||
if uint(s) > uint(len(src)) {
|
||||
return 1
|
||||
}
|
||||
x = uint32(src[s-3]) | uint32(src[s-2])<<8 | uint32(src[s-1])<<16
|
||||
case x == 63:
|
||||
s += 5
|
||||
if uint(s) > uint(len(src)) {
|
||||
return 1
|
||||
}
|
||||
x = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24
|
||||
}
|
||||
length = int(x) + 1
|
||||
if length <= 0 || length > len(dst)-d || length > len(src)-s {
|
||||
return 1
|
||||
}
|
||||
copy(dst[d:], src[s:s+length])
|
||||
d += length
|
||||
s += length
|
||||
continue
|
||||
case 0x01:
|
||||
s += 2
|
||||
if uint(s) > uint(len(src)) {
|
||||
return 1
|
||||
}
|
||||
length = 4 + int(src[s-2])>>2&0x7
|
||||
offset = int(uint32(src[s-2])&0xe0<<3 | uint32(src[s-1]))
|
||||
case 0x02:
|
||||
s += 3
|
||||
if uint(s) > uint(len(src)) {
|
||||
return 1
|
||||
}
|
||||
length = 1 + int(src[s-3])>>2
|
||||
offset = int(uint32(src[s-2]) | uint32(src[s-1])<<8)
|
||||
case 0x03:
|
||||
s += 5
|
||||
if uint(s) > uint(len(src)) {
|
||||
return 1
|
||||
}
|
||||
length = 1 + int(src[s-5])>>2
|
||||
offset = int(uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24)
|
||||
}
|
||||
if offset <= 0 || d < offset || length > len(dst)-d {
|
||||
return 1
|
||||
}
|
||||
if offset >= length {
|
||||
copy(dst[d:d+length], dst[d-offset:])
|
||||
d += length
|
||||
continue
|
||||
}
|
||||
a := dst[d : d+length]
|
||||
b := dst[d-offset:]
|
||||
b = b[:len(a)]
|
||||
for i := range a {
|
||||
a[i] = b[i]
|
||||
}
|
||||
d += length
|
||||
}
|
||||
if d != len(dst) {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
+35
-2
@@ -75,14 +75,47 @@ The above is fine for big encodes. However, whenever possible try to *reuse* the
|
||||
To reuse the encoder, you can use the `Reset(io.Writer)` function to change to another output.
|
||||
This will allow the encoder to reuse all resources and avoid wasteful allocations.
|
||||
|
||||
Currently stream encoding has 'light' concurrency, meaning up to 2 goroutines can be working on part
|
||||
of a stream. This is independent of the `WithEncoderConcurrency(n)`, but that is likely to change
|
||||
By default, stream encoding has 'light' concurrency, meaning up to 2 goroutines can be working on part
|
||||
of a stream. This is independent of the `WithEncoderConcurrency(n)`, but that is likely to change
|
||||
in the future. So if you want to limit concurrency for future updates, specify the concurrency
|
||||
you would like.
|
||||
|
||||
If you would like stream encoding to be done without spawning async goroutines, use `WithEncoderConcurrency(1)`
|
||||
which will compress input as each block is completed, blocking on writes until each has completed.
|
||||
|
||||
#### Parallel Stream Compression
|
||||
|
||||
For maximum throughput on large streams, use `WithConcurrentBlocks(true)` together with
|
||||
`WithEncoderConcurrency(n)` where n is the number of CPU cores you want to use.
|
||||
This splits the input into large sections (jobs) that are compressed simultaneously by multiple goroutines,
|
||||
similar to how the C zstd library does multithreaded compression.
|
||||
|
||||
```Go
|
||||
enc, err := zstd.NewWriter(out,
|
||||
zstd.WithEncoderLevel(zstd.SpeedDefault),
|
||||
zstd.WithEncoderConcurrency(runtime.GOMAXPROCS(0)),
|
||||
zstd.WithConcurrentBlocks(true),
|
||||
)
|
||||
```
|
||||
|
||||
Each non-first job receives an overlap prefix from the previous job for match context,
|
||||
so compression ratio is only marginally affected. Output is flushed in order,
|
||||
producing a valid single-frame zstd stream.
|
||||
|
||||
Benchmark on 1.8GB GOB stream (AMD Ryzen 9 9950X):
|
||||
|
||||
| Level | 1 thread | 4 threads | 16 threads | 1T ratio | 16T ratio |
|
||||
|---------|:----------:|:------------------:|:-------------------:|:--------:|:---------:|
|
||||
| fastest | 783 MB/s | 2950 MB/s (3.8×) | 6939 MB/s (8.9×) | 12.24% | 12.26% |
|
||||
| default | 728 MB/s | 2533 MB/s (3.5×) | 5340 MB/s (7.3×) | 10.67% | 10.68% |
|
||||
| better | 434 MB/s | 1105 MB/s (2.5×) | 2206 MB/s (5.1×) | 9.14% | 9.21% |
|
||||
| best | 129 MB/s | 367 MB/s (2.8×) | 884 MB/s (6.8×) | 8.48% | 8.63% |
|
||||
|
||||
Notes:
|
||||
* Not compatible with dictionary encoding.
|
||||
* `Flush()` dispatches the current partial job, so latency-sensitive callers can force output.
|
||||
* `EncodeAll` is unaffected — it uses its own concurrency via the encoder pool.
|
||||
|
||||
You can specify your desired compression level using `WithEncoderLevel()` option. Currently only pre-defined
|
||||
compression settings can be specified.
|
||||
|
||||
|
||||
+2
-1
@@ -230,7 +230,7 @@ func BuildDict(o BuildDictOptions) ([]byte, error) {
|
||||
}
|
||||
block := blockEnc{lowMem: false}
|
||||
block.init()
|
||||
enc := encoder(&bestFastEncoder{fastBase: fastBase{maxMatchOff: int32(maxMatchLen), bufferReset: math.MaxInt32 - int32(maxMatchLen*2), lowMem: false}})
|
||||
var enc encoder
|
||||
if o.Level != 0 {
|
||||
eOpts := encoderOptions{
|
||||
level: o.Level,
|
||||
@@ -242,6 +242,7 @@ func BuildDict(o BuildDictOptions) ([]byte, error) {
|
||||
enc = eOpts.encoder()
|
||||
} else {
|
||||
o.Level = SpeedBestCompression
|
||||
enc = encoder(&bestFastEncoder{fastBase: fastBase{maxMatchOff: int32(maxMatchLen), bufferReset: math.MaxInt32 - int32(maxMatchLen*2), lowMem: false}})
|
||||
}
|
||||
var (
|
||||
remain [256]int
|
||||
|
||||
+28
@@ -128,6 +128,34 @@ func (e *fastBase) matchlen(s, t int32, src []byte) int32 {
|
||||
return int32(matchLen(src[s:], src[t:]))
|
||||
}
|
||||
|
||||
// resetBasePrefix resets the encoder state and loads prefix as initial history.
|
||||
// This is used for parallel job encoding where non-first jobs need overlap context.
|
||||
// Rep offsets are set to defaults [1,4,8] (invalidated, matching C behavior).
|
||||
func (e *fastBase) resetBasePrefix(prefix []byte) {
|
||||
if e.blk == nil {
|
||||
e.blk = &blockEnc{lowMem: e.lowMem}
|
||||
e.blk.init()
|
||||
} else {
|
||||
e.blk.reset(nil)
|
||||
}
|
||||
e.blk.initNewEncode()
|
||||
if e.crc == nil {
|
||||
e.crc = xxhash.New()
|
||||
} else {
|
||||
e.crc.Reset()
|
||||
}
|
||||
e.blk.dictLitEnc = nil
|
||||
e.ensureHist(len(prefix) + maxCompressedBlockSize)
|
||||
// Bump cur so old table entries fall outside the window.
|
||||
// When cur >= bufferReset, leave it; the first Encode call
|
||||
// will shift/clear tables, preserving valid prefix entries.
|
||||
if e.cur < e.bufferReset {
|
||||
e.cur += e.maxMatchOff + int32(len(e.hist))
|
||||
}
|
||||
e.hist = e.hist[:0]
|
||||
e.hist = append(e.hist, prefix...)
|
||||
}
|
||||
|
||||
// Reset the encoding table.
|
||||
func (e *fastBase) resetBase(d *dict, singleBlock bool) {
|
||||
if e.blk == nil {
|
||||
|
||||
+15
@@ -551,3 +551,18 @@ func (e *bestFastEncoder) Reset(d *dict, singleBlock bool) {
|
||||
// Reset table to initial state
|
||||
copy(e.table[:], e.dictTable)
|
||||
}
|
||||
|
||||
func (e *bestFastEncoder) ResetPrefix(prefix []byte) {
|
||||
e.resetBasePrefix(prefix)
|
||||
if len(prefix) < 8 {
|
||||
return
|
||||
}
|
||||
end := e.cur + int32(len(prefix)) - 8
|
||||
for i := e.cur; i < end; i++ {
|
||||
cv := load6432(prefix, i-e.cur)
|
||||
h := hashLen(cv, bestLongTableBits, bestLongLen)
|
||||
e.longTable[h] = prevEntry{offset: i, prev: e.longTable[h].offset}
|
||||
h0 := hashLen(cv, bestShortTableBits, bestShortLen)
|
||||
e.table[h0] = prevEntry{offset: i, prev: e.table[h0].offset}
|
||||
}
|
||||
}
|
||||
+18
@@ -1096,6 +1096,20 @@ func (e *betterFastEncoder) Reset(d *dict, singleBlock bool) {
|
||||
}
|
||||
}
|
||||
|
||||
func (e *betterFastEncoder) ResetPrefix(prefix []byte) {
|
||||
e.resetBasePrefix(prefix)
|
||||
if len(prefix) < 8 {
|
||||
return
|
||||
}
|
||||
end := e.cur + int32(len(prefix)) - 8
|
||||
for i := e.cur; i < end; i += 2 {
|
||||
cv := load6432(prefix, i-e.cur)
|
||||
h := hashLen(cv, betterLongTableBits, betterLongLen)
|
||||
e.longTable[h] = prevEntry{offset: i, prev: e.longTable[h].offset}
|
||||
e.table[hashLen(cv>>8, betterShortTableBits, betterShortLen)] = tableEntry{val: uint32(cv >> 8), offset: i + 1}
|
||||
}
|
||||
}
|
||||
|
||||
// ResetDict will reset and set a dictionary if not nil
|
||||
func (e *betterFastEncoderDict) Reset(d *dict, singleBlock bool) {
|
||||
e.resetBase(d, singleBlock)
|
||||
@@ -1229,6 +1243,10 @@ func (e *betterFastEncoderDict) Reset(d *dict, singleBlock bool) {
|
||||
e.allDirty = false
|
||||
}
|
||||
|
||||
func (e *betterFastEncoderDict) ResetPrefix([]byte) {
|
||||
panic("ResetPrefix not supported for dict encoders")
|
||||
}
|
||||
|
||||
func (e *betterFastEncoderDict) markLongShardDirty(entryNum uint32) {
|
||||
e.longTableShardDirty[entryNum/betterLongTableShardSize] = true
|
||||
}
|
||||
|
||||
+16
@@ -1037,6 +1037,18 @@ func (e *doubleFastEncoder) Reset(d *dict, singleBlock bool) {
|
||||
}
|
||||
}
|
||||
|
||||
func (e *doubleFastEncoder) ResetPrefix(prefix []byte) {
|
||||
e.fastEncoder.ResetPrefix(prefix)
|
||||
if len(prefix) < 8 {
|
||||
return
|
||||
}
|
||||
end := e.cur + int32(len(prefix)) - 8
|
||||
for i := e.cur + 1; i < end; i += 2 {
|
||||
cv := load6432(prefix, i-e.cur)
|
||||
e.longTable[hashLen(cv, dFastLongTableBits, dFastLongLen)] = tableEntry{val: uint32(cv), offset: i}
|
||||
}
|
||||
}
|
||||
|
||||
// ResetDict will reset and set a dictionary if not nil
|
||||
func (e *doubleFastEncoderDict) Reset(d *dict, singleBlock bool) {
|
||||
allDirty := e.allDirty
|
||||
@@ -1102,6 +1114,10 @@ func (e *doubleFastEncoderDict) Reset(d *dict, singleBlock bool) {
|
||||
}
|
||||
}
|
||||
|
||||
func (e *doubleFastEncoderDict) ResetPrefix([]byte) {
|
||||
panic("ResetPrefix not supported for dict encoders")
|
||||
}
|
||||
|
||||
func (e *doubleFastEncoderDict) markLongShardDirty(entryNum uint32) {
|
||||
e.longTableShardDirty[entryNum/dLongTableShardSize] = true
|
||||
}
|
||||
+17
@@ -797,6 +797,19 @@ func (e *fastEncoder) Reset(d *dict, singleBlock bool) {
|
||||
}
|
||||
}
|
||||
|
||||
func (e *fastEncoder) ResetPrefix(prefix []byte) {
|
||||
e.resetBasePrefix(prefix)
|
||||
if len(prefix) < 8 {
|
||||
return
|
||||
}
|
||||
end := e.cur + int32(len(prefix)) - 8
|
||||
// Index every 4th
|
||||
for i := e.cur + 1; i < end; i += 4 {
|
||||
cv := load6432(prefix, i-e.cur)
|
||||
e.table[hashLen(cv, tableBits, tableFastHashLen)] = tableEntry{val: uint32(cv), offset: i}
|
||||
}
|
||||
}
|
||||
|
||||
// ResetDict will reset and set a dictionary if not nil
|
||||
func (e *fastEncoderDict) Reset(d *dict, singleBlock bool) {
|
||||
e.resetBase(d, singleBlock)
|
||||
@@ -866,6 +879,10 @@ func (e *fastEncoderDict) Reset(d *dict, singleBlock bool) {
|
||||
e.allDirty = false
|
||||
}
|
||||
|
||||
func (e *fastEncoderDict) ResetPrefix([]byte) {
|
||||
panic("ResetPrefix not supported for dict encoders")
|
||||
}
|
||||
|
||||
func (e *fastEncoderDict) markAllShardsDirty() {
|
||||
e.allDirty = true
|
||||
}
|
||||
|
||||
+352
@@ -0,0 +1,352 @@
|
||||
// Copyright 2019+ Klaus Post. All rights reserved.
|
||||
// License information can be found in the LICENSE file.
|
||||
// Based on work by Yann Collet, released under BSD License.
|
||||
|
||||
package zstd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
rdebug "runtime/debug"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type encJob struct {
|
||||
prefix []byte // overlap from previous job (nil for first)
|
||||
input []byte // job's own input data (swapped from filling)
|
||||
last bool // last block of last job gets last=true
|
||||
output []byte // compressed blocks (filled by worker)
|
||||
err error // encoding error
|
||||
done chan struct{} // closed when complete
|
||||
}
|
||||
|
||||
type jobState struct {
|
||||
jobSize int
|
||||
overlapSize int
|
||||
filling []byte // accumulates input up to jobSize
|
||||
nextPrefix []byte // overlap prefix prepared for the next dispatched job
|
||||
|
||||
jobSeq int // next job sequence number
|
||||
|
||||
jobCh chan *encJob // dispatch to workers
|
||||
resultCh chan *encJob // ordered results to flusher
|
||||
|
||||
workerWg sync.WaitGroup
|
||||
flusherWg sync.WaitGroup
|
||||
|
||||
mu sync.Mutex
|
||||
flushedSeq int // last flushed sequence number
|
||||
cond *sync.Cond
|
||||
|
||||
flusherErr error
|
||||
started bool
|
||||
|
||||
inputPool sync.Pool // *[]byte buffers of jobSize cap
|
||||
outputPool sync.Pool // *[]byte buffers for compressed output
|
||||
overlapPool sync.Pool // *[]byte buffers for overlap prefixes
|
||||
}
|
||||
|
||||
func (e *Encoder) startJobWorkers() {
|
||||
js := &e.state.jobs
|
||||
n := e.o.concurrent
|
||||
js.jobCh = make(chan *encJob, n)
|
||||
js.resultCh = make(chan *encJob, n)
|
||||
js.flushedSeq = 0
|
||||
js.cond = sync.NewCond(&js.mu)
|
||||
|
||||
// Workers borrow encoders from the shared e.encoders pool per-job.
|
||||
// Ensure the pool is initialized before any worker tries to borrow.
|
||||
e.init.Do(e.initialize)
|
||||
|
||||
for range n {
|
||||
js.workerWg.Add(1)
|
||||
go e.jobWorker()
|
||||
}
|
||||
js.flusherWg.Add(1)
|
||||
go e.jobFlusher()
|
||||
js.started = true
|
||||
}
|
||||
|
||||
func (e *Encoder) jobWorker() {
|
||||
js := &e.state.jobs
|
||||
defer js.workerWg.Done()
|
||||
for job := range js.jobCh {
|
||||
enc := <-e.encoders
|
||||
e.compressJob(enc, job)
|
||||
e.encoders <- enc
|
||||
close(job.done)
|
||||
}
|
||||
}
|
||||
|
||||
func (e *Encoder) compressJob(enc encoder, job *encJob) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
job.err = fmt.Errorf("panic in parallel job: %v", r)
|
||||
rdebug.PrintStack()
|
||||
}
|
||||
}()
|
||||
|
||||
if len(job.prefix) > 0 {
|
||||
enc.ResetPrefix(job.prefix)
|
||||
} else {
|
||||
enc.Reset(nil, false)
|
||||
}
|
||||
|
||||
data := job.input
|
||||
if len(data) == 0 && job.last {
|
||||
blk := enc.Block()
|
||||
blk.reset(nil)
|
||||
blk.last = true
|
||||
blk.encodeRaw(nil)
|
||||
job.output = append(job.output, blk.output...)
|
||||
return
|
||||
}
|
||||
|
||||
blk := enc.Block()
|
||||
for len(data) > 0 {
|
||||
todo := data
|
||||
if len(todo) > e.o.blockSize {
|
||||
todo = todo[:e.o.blockSize]
|
||||
}
|
||||
data = data[len(todo):]
|
||||
|
||||
blk.pushOffsets()
|
||||
enc.Encode(blk, todo)
|
||||
blk.last = len(data) == 0 && job.last
|
||||
|
||||
err := blk.encode(todo, e.o.noEntropy, !e.o.allLitEntropy)
|
||||
if err != nil {
|
||||
job.err = err
|
||||
return
|
||||
}
|
||||
job.output = append(job.output, blk.output...)
|
||||
blk.reset(nil)
|
||||
}
|
||||
}
|
||||
|
||||
func (js *jobState) getInputBuf(size int) []byte {
|
||||
if v := js.inputPool.Get(); v != nil {
|
||||
bp := v.(*[]byte)
|
||||
b := *bp
|
||||
if cap(b) >= size {
|
||||
return b[:0]
|
||||
}
|
||||
}
|
||||
return make([]byte, 0, size)
|
||||
}
|
||||
|
||||
func (js *jobState) putInputBuf(b []byte) {
|
||||
if cap(b) > 0 {
|
||||
b = b[:0]
|
||||
js.inputPool.Put(&b)
|
||||
}
|
||||
}
|
||||
|
||||
func (js *jobState) getOutputBuf(size int) []byte {
|
||||
if v := js.outputPool.Get(); v != nil {
|
||||
bp := v.(*[]byte)
|
||||
b := *bp
|
||||
if cap(b) >= size {
|
||||
return b[:0]
|
||||
}
|
||||
}
|
||||
return make([]byte, 0, size)
|
||||
}
|
||||
|
||||
func (js *jobState) putOutputBuf(b []byte) {
|
||||
if cap(b) > 0 {
|
||||
b = b[:0]
|
||||
js.outputPool.Put(&b)
|
||||
}
|
||||
}
|
||||
|
||||
func (js *jobState) getOverlapBuf(size int) []byte {
|
||||
if v := js.overlapPool.Get(); v != nil {
|
||||
bp := v.(*[]byte)
|
||||
b := *bp
|
||||
if cap(b) >= size {
|
||||
return b[:size]
|
||||
}
|
||||
}
|
||||
return make([]byte, size)
|
||||
}
|
||||
|
||||
func (js *jobState) putOverlapBuf(b []byte) {
|
||||
if cap(b) > 0 {
|
||||
b = b[:0]
|
||||
js.overlapPool.Put(&b)
|
||||
}
|
||||
}
|
||||
|
||||
func (e *Encoder) jobFlusher() {
|
||||
js := &e.state.jobs
|
||||
defer js.flusherWg.Done()
|
||||
for job := range js.resultCh {
|
||||
<-job.done
|
||||
// Worker has fully exited compressJob, so the prefix is no longer
|
||||
// in use. Return it to the pool regardless of outcome.
|
||||
if job.prefix != nil {
|
||||
js.putOverlapBuf(job.prefix)
|
||||
job.prefix = nil
|
||||
}
|
||||
if job.err != nil {
|
||||
js.mu.Lock()
|
||||
js.flusherErr = job.err
|
||||
js.cond.Broadcast()
|
||||
js.mu.Unlock()
|
||||
for range js.resultCh {
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(job.output) > 0 {
|
||||
_, err := e.state.w.Write(job.output)
|
||||
if err != nil {
|
||||
js.mu.Lock()
|
||||
js.flusherErr = err
|
||||
js.cond.Broadcast()
|
||||
js.mu.Unlock()
|
||||
for range js.resultCh {
|
||||
}
|
||||
return
|
||||
}
|
||||
e.state.nWritten += int64(len(job.output))
|
||||
}
|
||||
// Return buffers to pools.
|
||||
js.putInputBuf(job.input)
|
||||
js.putOutputBuf(job.output)
|
||||
job.input = nil
|
||||
job.output = nil
|
||||
|
||||
js.mu.Lock()
|
||||
js.flushedSeq++
|
||||
js.cond.Broadcast()
|
||||
js.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func (e *Encoder) shutdownJobWorkers() {
|
||||
js := &e.state.jobs
|
||||
if !js.started {
|
||||
return
|
||||
}
|
||||
close(js.jobCh)
|
||||
js.workerWg.Wait()
|
||||
close(js.resultCh)
|
||||
js.flusherWg.Wait()
|
||||
js.started = false
|
||||
}
|
||||
|
||||
// waitAllJobs blocks until all dispatched jobs have been flushed.
|
||||
func (e *Encoder) waitAllJobs() {
|
||||
js := &e.state.jobs
|
||||
if !js.started {
|
||||
return
|
||||
}
|
||||
js.mu.Lock()
|
||||
for js.flushedSeq < js.jobSeq && js.flusherErr == nil {
|
||||
js.cond.Wait()
|
||||
}
|
||||
js.mu.Unlock()
|
||||
}
|
||||
|
||||
func (e *Encoder) dispatchJob(final bool) error {
|
||||
s := &e.state
|
||||
js := &s.jobs
|
||||
|
||||
js.mu.Lock()
|
||||
fErr := js.flusherErr
|
||||
js.mu.Unlock()
|
||||
if fErr != nil {
|
||||
return fErr
|
||||
}
|
||||
|
||||
if !s.headerWritten {
|
||||
// Single-block optimization: fall through to encodeAll path.
|
||||
if final && len(js.filling) > 0 && len(js.filling) <= e.o.blockSize {
|
||||
s.current = e.encodeAll(s.encoder, js.filling, s.current[:0])
|
||||
var n2 int
|
||||
n2, s.err = s.w.Write(s.current)
|
||||
if s.err != nil {
|
||||
return s.err
|
||||
}
|
||||
s.nWritten += int64(n2)
|
||||
s.nInput += int64(len(js.filling))
|
||||
s.current = s.current[:0]
|
||||
js.filling = js.filling[:0]
|
||||
s.headerWritten = true
|
||||
s.fullFrameWritten = true
|
||||
s.eofWritten = true
|
||||
return nil
|
||||
}
|
||||
if final && len(js.filling) == 0 && !e.o.fullZero {
|
||||
s.headerWritten = true
|
||||
s.fullFrameWritten = true
|
||||
s.eofWritten = true
|
||||
return nil
|
||||
}
|
||||
|
||||
var tmp [maxHeaderSize]byte
|
||||
fh := frameHeader{
|
||||
ContentSize: uint64(s.frameContentSize),
|
||||
WindowSize: uint32(s.encoder.WindowSize(s.frameContentSize)),
|
||||
SingleSegment: false,
|
||||
Checksum: e.o.crc,
|
||||
DictID: 0,
|
||||
}
|
||||
dst := fh.appendTo(tmp[:0])
|
||||
var n2 int
|
||||
n2, s.err = s.w.Write(dst)
|
||||
if s.err != nil {
|
||||
return s.err
|
||||
}
|
||||
s.nWritten += int64(n2)
|
||||
s.headerWritten = true
|
||||
}
|
||||
|
||||
if len(js.filling) == 0 && !final {
|
||||
return nil
|
||||
}
|
||||
|
||||
if !js.started {
|
||||
e.startJobWorkers()
|
||||
}
|
||||
|
||||
// Estimate output size for pooled buffer.
|
||||
outputEst := max(len(js.filling)/2, 512)
|
||||
|
||||
job := &encJob{
|
||||
last: final,
|
||||
done: make(chan struct{}),
|
||||
output: js.getOutputBuf(outputEst),
|
||||
}
|
||||
|
||||
// Each job owns its prefix slice; the flusher returns it to the pool
|
||||
// after <-job.done, so workers and dispatch never share a buffer.
|
||||
if js.nextPrefix != nil {
|
||||
job.prefix = js.nextPrefix
|
||||
js.nextPrefix = nil
|
||||
}
|
||||
|
||||
// Build the next job's prefix from the tail of this job's input.
|
||||
if !final && len(js.filling) > 0 {
|
||||
overlapLen := min(js.overlapSize, len(js.filling))
|
||||
np := js.getOverlapBuf(overlapLen)
|
||||
copy(np, js.filling[len(js.filling)-overlapLen:])
|
||||
js.nextPrefix = np
|
||||
}
|
||||
|
||||
// Swap filling buffer into job — zero-copy for the input data.
|
||||
job.input = js.filling
|
||||
js.filling = js.getInputBuf(js.jobSize)
|
||||
|
||||
s.nInput += int64(len(job.input))
|
||||
js.jobSeq++
|
||||
|
||||
if final {
|
||||
s.eofWritten = true
|
||||
}
|
||||
|
||||
js.resultCh <- job
|
||||
js.jobCh <- job
|
||||
|
||||
return nil
|
||||
}
|
||||
+206
-4
@@ -38,6 +38,7 @@ type encoder interface {
|
||||
WindowSize(size int64) int32
|
||||
UseBlock(*blockEnc)
|
||||
Reset(d *dict, singleBlock bool)
|
||||
ResetPrefix(prefix []byte)
|
||||
}
|
||||
|
||||
type encoderState struct {
|
||||
@@ -60,6 +61,9 @@ type encoderState struct {
|
||||
wg sync.WaitGroup
|
||||
// This waitgroup indicates we have a block encoding/writing.
|
||||
wWg sync.WaitGroup
|
||||
|
||||
// Parallel job state (used when concurrentBlocks is enabled).
|
||||
jobs jobState
|
||||
}
|
||||
|
||||
// NewWriter will create a new Zstandard encoder.
|
||||
@@ -74,6 +78,9 @@ func NewWriter(w io.Writer, opts ...EOption) (*Encoder, error) {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if e.o.concurrentBlocks && (e.o.dict != nil || e.o.concurrent <= 1) {
|
||||
e.o.concurrentBlocks = false
|
||||
}
|
||||
if w != nil {
|
||||
e.Reset(w)
|
||||
}
|
||||
@@ -95,12 +102,31 @@ func (e *Encoder) initialize() {
|
||||
// as a new, independent stream.
|
||||
func (e *Encoder) Reset(w io.Writer) {
|
||||
s := &e.state
|
||||
|
||||
if e.o.concurrentBlocks {
|
||||
e.shutdownJobWorkers()
|
||||
js := &s.jobs
|
||||
js.jobSize = e.o.jobSize()
|
||||
js.overlapSize = e.o.overlapSize()
|
||||
// js.filling is allocated lazily on first Write/ReadFrom so callers
|
||||
// that only use EncodeAll don't pay the (up to ~32 MB) jobSize cost.
|
||||
js.filling = js.filling[:0]
|
||||
if js.nextPrefix != nil {
|
||||
js.putOverlapBuf(js.nextPrefix)
|
||||
js.nextPrefix = nil
|
||||
}
|
||||
js.jobSeq = 0
|
||||
js.flushedSeq = 0
|
||||
js.flusherErr = nil
|
||||
js.started = false
|
||||
}
|
||||
|
||||
s.wg.Wait()
|
||||
s.wWg.Wait()
|
||||
if cap(s.filling) == 0 {
|
||||
s.filling = make([]byte, 0, e.o.blockSize)
|
||||
}
|
||||
if e.o.concurrent > 1 {
|
||||
if e.o.concurrent > 1 && !e.o.concurrentBlocks {
|
||||
if cap(s.current) == 0 {
|
||||
s.current = make([]byte, 0, e.o.blockSize)
|
||||
}
|
||||
@@ -145,6 +171,9 @@ func (e *Encoder) ResetWithOptions(w io.Writer, opts ...EOption) error {
|
||||
}
|
||||
}
|
||||
hasDict := e.o.dict != nil
|
||||
if e.o.concurrentBlocks && hasDict {
|
||||
e.o.concurrentBlocks = false
|
||||
}
|
||||
if hadDict != hasDict {
|
||||
// Dict presence changed — encoder type must be recreated.
|
||||
e.state.encoder = nil
|
||||
@@ -176,6 +205,49 @@ func (e *Encoder) Write(p []byte) (n int, err error) {
|
||||
if s.eofWritten {
|
||||
return 0, ErrEncoderClosed
|
||||
}
|
||||
if e.o.concurrentBlocks {
|
||||
return e.writeJobs(p)
|
||||
}
|
||||
return e.writeBlocks(p)
|
||||
}
|
||||
|
||||
func (e *Encoder) writeJobs(p []byte) (n int, err error) {
|
||||
s := &e.state
|
||||
js := &s.jobs
|
||||
jobSize := js.jobSize
|
||||
if cap(js.filling) == 0 && len(p) > 0 {
|
||||
js.filling = make([]byte, 0, jobSize)
|
||||
}
|
||||
for len(p) > 0 {
|
||||
if len(p)+len(js.filling) < jobSize {
|
||||
if e.o.crc {
|
||||
_, _ = s.encoder.CRC().Write(p)
|
||||
}
|
||||
js.filling = append(js.filling, p...)
|
||||
return n + len(p), nil
|
||||
}
|
||||
add := p
|
||||
if len(p)+len(js.filling) > jobSize {
|
||||
add = add[:jobSize-len(js.filling)]
|
||||
}
|
||||
if e.o.crc {
|
||||
_, _ = s.encoder.CRC().Write(add)
|
||||
}
|
||||
js.filling = append(js.filling, add...)
|
||||
p = p[len(add):]
|
||||
n += len(add)
|
||||
if len(js.filling) < jobSize {
|
||||
return n, nil
|
||||
}
|
||||
if err := e.dispatchJob(false); err != nil {
|
||||
return n, err
|
||||
}
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (e *Encoder) writeBlocks(p []byte) (n int, err error) {
|
||||
s := &e.state
|
||||
for len(p) > 0 {
|
||||
if len(p)+len(s.filling) < e.o.blockSize {
|
||||
if e.o.crc {
|
||||
@@ -374,6 +446,10 @@ func (e *Encoder) ReadFrom(r io.Reader) (n int64, err error) {
|
||||
println("Using ReadFrom")
|
||||
}
|
||||
|
||||
if e.o.concurrentBlocks {
|
||||
return e.readFromJobs(r)
|
||||
}
|
||||
|
||||
// Flush any current writes.
|
||||
if len(e.state.filling) > 0 {
|
||||
if err := e.nextBlock(false); err != nil {
|
||||
@@ -387,7 +463,6 @@ func (e *Encoder) ReadFrom(r io.Reader) (n int64, err error) {
|
||||
if e.o.crc {
|
||||
_, _ = e.state.encoder.CRC().Write(src[:n2])
|
||||
}
|
||||
// src is now the unfilled part...
|
||||
src = src[n2:]
|
||||
n += int64(n2)
|
||||
switch err {
|
||||
@@ -420,15 +495,63 @@ func (e *Encoder) ReadFrom(r io.Reader) (n int64, err error) {
|
||||
}
|
||||
}
|
||||
|
||||
func (e *Encoder) readFromJobs(r io.Reader) (n int64, err error) {
|
||||
js := &e.state.jobs
|
||||
jobSize := js.jobSize
|
||||
|
||||
// Flush any current filling.
|
||||
if len(js.filling) > 0 {
|
||||
if err := e.dispatchJob(false); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
if cap(js.filling) < jobSize {
|
||||
js.filling = make([]byte, 0, jobSize)
|
||||
}
|
||||
js.filling = js.filling[:jobSize]
|
||||
src := js.filling
|
||||
for {
|
||||
n2, err := r.Read(src)
|
||||
if e.o.crc {
|
||||
_, _ = e.state.encoder.CRC().Write(src[:n2])
|
||||
}
|
||||
src = src[n2:]
|
||||
n += int64(n2)
|
||||
switch err {
|
||||
case io.EOF:
|
||||
js.filling = js.filling[:len(js.filling)-len(src)]
|
||||
return n, nil
|
||||
case nil:
|
||||
default:
|
||||
e.state.err = err
|
||||
return n, err
|
||||
}
|
||||
if len(src) > 0 {
|
||||
continue
|
||||
}
|
||||
if err = e.dispatchJob(false); err != nil {
|
||||
return n, err
|
||||
}
|
||||
if cap(js.filling) < jobSize {
|
||||
js.filling = make([]byte, 0, jobSize)
|
||||
}
|
||||
js.filling = js.filling[:jobSize]
|
||||
src = js.filling
|
||||
}
|
||||
}
|
||||
|
||||
// Flush will send the currently written data to output
|
||||
// and block until everything has been written.
|
||||
// This should only be used on rare occasions where pushing the currently queued data is critical.
|
||||
func (e *Encoder) Flush() error {
|
||||
s := &e.state
|
||||
if e.o.concurrentBlocks {
|
||||
return e.flushJobs()
|
||||
}
|
||||
if len(s.filling) > 0 {
|
||||
err := e.nextBlock(false)
|
||||
if err != nil {
|
||||
// Ignore Flush after Close.
|
||||
if errors.Is(s.err, ErrEncoderClosed) {
|
||||
return nil
|
||||
}
|
||||
@@ -438,7 +561,6 @@ func (e *Encoder) Flush() error {
|
||||
s.wg.Wait()
|
||||
s.wWg.Wait()
|
||||
if s.err != nil {
|
||||
// Ignore Flush after Close.
|
||||
if errors.Is(s.err, ErrEncoderClosed) {
|
||||
return nil
|
||||
}
|
||||
@@ -447,6 +569,20 @@ func (e *Encoder) Flush() error {
|
||||
return s.writeErr
|
||||
}
|
||||
|
||||
func (e *Encoder) flushJobs() error {
|
||||
js := &e.state.jobs
|
||||
if len(js.filling) > 0 {
|
||||
if err := e.dispatchJob(false); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
e.waitAllJobs()
|
||||
js.mu.Lock()
|
||||
fErr := js.flusherErr
|
||||
js.mu.Unlock()
|
||||
return fErr
|
||||
}
|
||||
|
||||
// Close will flush the final output and close the stream.
|
||||
// The function will block until everything has been written.
|
||||
// The Encoder can still be re-used after calling this.
|
||||
@@ -455,12 +591,16 @@ func (e *Encoder) Close() error {
|
||||
if s.encoder == nil {
|
||||
return nil
|
||||
}
|
||||
if e.o.concurrentBlocks {
|
||||
return e.closeJobs()
|
||||
}
|
||||
if s.w == nil {
|
||||
if len(s.filling) == 0 && !s.headerWritten && !s.eofWritten && s.nInput == 0 {
|
||||
return nil
|
||||
}
|
||||
return errors.New("zstd: encoder has no writer")
|
||||
}
|
||||
|
||||
err := e.nextBlock(true)
|
||||
if err != nil {
|
||||
if errors.Is(s.err, ErrEncoderClosed) {
|
||||
@@ -511,6 +651,68 @@ func (e *Encoder) Close() error {
|
||||
return s.err
|
||||
}
|
||||
|
||||
func (e *Encoder) closeJobs() error {
|
||||
s := &e.state
|
||||
js := &s.jobs
|
||||
|
||||
if errors.Is(s.err, ErrEncoderClosed) {
|
||||
return nil
|
||||
}
|
||||
|
||||
if s.w == nil {
|
||||
if len(js.filling) == 0 && !s.headerWritten && !s.eofWritten && s.nInput == 0 {
|
||||
return nil
|
||||
}
|
||||
return errors.New("zstd: encoder has no writer")
|
||||
}
|
||||
|
||||
if err := e.dispatchJob(true); err != nil {
|
||||
e.shutdownJobWorkers()
|
||||
if errors.Is(s.err, ErrEncoderClosed) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if s.frameContentSize > 0 && s.nInput != s.frameContentSize {
|
||||
e.shutdownJobWorkers()
|
||||
return fmt.Errorf("frame content size %d given, but %d bytes was written", s.frameContentSize, s.nInput)
|
||||
}
|
||||
|
||||
if s.fullFrameWritten {
|
||||
e.shutdownJobWorkers()
|
||||
s.err = ErrEncoderClosed
|
||||
return nil
|
||||
}
|
||||
|
||||
e.shutdownJobWorkers()
|
||||
if js.flusherErr != nil {
|
||||
return js.flusherErr
|
||||
}
|
||||
|
||||
// Write CRC
|
||||
if e.o.crc {
|
||||
var tmp [4]byte
|
||||
_, s.err = s.w.Write(s.encoder.AppendCRC(tmp[:0]))
|
||||
s.nWritten += 4
|
||||
}
|
||||
|
||||
// Add padding
|
||||
if s.err == nil && e.o.pad > 0 {
|
||||
add := calcSkippableFrame(s.nWritten, int64(e.o.pad))
|
||||
frame, err := skippableFrame(js.filling[:0], add, rand.Reader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, s.err = s.w.Write(frame)
|
||||
}
|
||||
if s.err == nil {
|
||||
s.err = ErrEncoderClosed
|
||||
return nil
|
||||
}
|
||||
return s.err
|
||||
}
|
||||
|
||||
// EncodeAll will encode all input in src and append it to dst.
|
||||
// This function can be called concurrently, but each call will only run on a single goroutine.
|
||||
// If empty input is given, nothing is returned, unless WithZeroFrames is specified.
|
||||
|
||||
+53
-16
@@ -14,22 +14,23 @@ type EOption func(*encoderOptions) error
|
||||
|
||||
// options retains accumulated state of multiple options.
|
||||
type encoderOptions struct {
|
||||
resetOpt bool
|
||||
concurrent int
|
||||
level EncoderLevel
|
||||
single *bool
|
||||
pad int
|
||||
blockSize int
|
||||
windowSize int
|
||||
crc bool
|
||||
fullZero bool
|
||||
noEntropy bool
|
||||
allLitEntropy bool
|
||||
customWindow bool
|
||||
customALEntropy bool
|
||||
customBlockSize bool
|
||||
lowMem bool
|
||||
dict *dict
|
||||
resetOpt bool
|
||||
concurrent int
|
||||
level EncoderLevel
|
||||
single *bool
|
||||
pad int
|
||||
blockSize int
|
||||
windowSize int
|
||||
crc bool
|
||||
fullZero bool
|
||||
noEntropy bool
|
||||
allLitEntropy bool
|
||||
customWindow bool
|
||||
customALEntropy bool
|
||||
customBlockSize bool
|
||||
lowMem bool
|
||||
dict *dict
|
||||
concurrentBlocks bool
|
||||
}
|
||||
|
||||
func (o *encoderOptions) setDefault() {
|
||||
@@ -333,6 +334,42 @@ func WithLowerEncoderMem(b bool) EOption {
|
||||
}
|
||||
}
|
||||
|
||||
// WithConcurrentBlocks enables job-based parallel compression for streams.
|
||||
// When enabled and concurrent > 1, input is split into large sections (jobs)
|
||||
// that are compressed simultaneously by multiple goroutines.
|
||||
// Each non-first job receives an overlap prefix from the previous job for match context.
|
||||
// Output is flushed in order, producing a valid single-frame zstd stream.
|
||||
//
|
||||
// Currently disabled when used with dictionary encoding.
|
||||
// Cannot be changed with ResetWithOptions.
|
||||
func WithConcurrentBlocks(b bool) EOption {
|
||||
return func(o *encoderOptions) error {
|
||||
if o.resetOpt && b != o.concurrentBlocks {
|
||||
return errors.New("WithConcurrentBlocks cannot be changed on Reset")
|
||||
}
|
||||
o.concurrentBlocks = b
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// jobSize returns the input section size per parallel job.
|
||||
func (o *encoderOptions) jobSize() int {
|
||||
s := max(o.windowSize*4, 512<<10)
|
||||
return s
|
||||
}
|
||||
|
||||
// overlapSize returns the overlap prefix size for parallel jobs.
|
||||
func (o *encoderOptions) overlapSize() int {
|
||||
switch o.level {
|
||||
case SpeedBestCompression:
|
||||
return o.windowSize / 2
|
||||
case SpeedBetterCompression:
|
||||
return o.windowSize / 4
|
||||
default:
|
||||
return o.windowSize / 8
|
||||
}
|
||||
}
|
||||
|
||||
// WithEncoderDict allows to register a dictionary that will be used for the encode.
|
||||
//
|
||||
// The slice dict must be in the [dictionary format] produced by
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
// Code generated by command: go run gen_fse.go -out ../fse_decoder_amd64.s -pkg=zstd. DO NOT EDIT.
|
||||
// Code generated by command: go run gen_fse.go -out ../fse_decoder.s -arch amd64,arm64 -pkg=zstd. DO NOT EDIT.
|
||||
|
||||
//go:build !appengine && !noasm && gc && !noasm
|
||||
|
||||
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
// Code generated by command: go run gen_fse.go -out ../fse_decoder.s -arch amd64,arm64 -pkg=zstd. DO NOT EDIT.
|
||||
// EXPERIMENTAL arm64 output lowered from an amd64 avo program.
|
||||
|
||||
//go:build arm64 && !appengine && !noasm && gc && !noasm
|
||||
|
||||
// func buildDtable_asm(s *fseDecoder, ctx *buildDtableAsmContext) int
|
||||
TEXT ·buildDtable_asm(SB), $0-24
|
||||
MOVD ctx+8(FP), R1
|
||||
MOVD s+0(FP), R6
|
||||
|
||||
// Load values
|
||||
MOVBU 4098(R6), R2
|
||||
MOVD $0, R0
|
||||
MOVD $1, R16
|
||||
LSL R2, R16, R16
|
||||
ORR R16, R0, R0
|
||||
MOVD (R1), R3
|
||||
MOVD 16(R1), R5
|
||||
SUB $1, R0, R7
|
||||
MOVD 8(R1), R1
|
||||
MOVHU 4096(R6), R6
|
||||
|
||||
// End load values
|
||||
// Init, lay down lowprob symbols
|
||||
MOVD $0, R8
|
||||
JMP init_main_loop_condition
|
||||
|
||||
init_main_loop:
|
||||
ADD R8<<1, R1, R15
|
||||
MOVH (R15), R9
|
||||
AND $0xffff, R9, R15
|
||||
MOVD $-1, R16
|
||||
AND $0xffff, R16, R16
|
||||
CMP R16, R15
|
||||
BNE do_not_update_high_threshold
|
||||
ADD R7<<3, R5, R15
|
||||
MOVB R8, 1(R15)
|
||||
SUB $1, R7, R7
|
||||
MOVD $0x0000000000000001, R9
|
||||
|
||||
do_not_update_high_threshold:
|
||||
ADD R8<<1, R3, R15
|
||||
MOVH R9, (R15)
|
||||
ADD $1, R8, R8
|
||||
|
||||
init_main_loop_condition:
|
||||
CMP R6, R8
|
||||
BLT init_main_loop
|
||||
|
||||
// Spread symbols
|
||||
// Calculate table step
|
||||
MOVD R0, R8
|
||||
LSR $0x01, R8, R8
|
||||
MOVD R0, R9
|
||||
LSR $0x03, R9, R9
|
||||
ADD R9, R8, R8
|
||||
ADD $3, R8, R8
|
||||
|
||||
// Fill add bits values
|
||||
SUB $1, R0, R9
|
||||
MOVD $0, R10
|
||||
MOVD $0, R11
|
||||
JMP spread_main_loop_condition
|
||||
|
||||
spread_main_loop:
|
||||
MOVD $0, R12
|
||||
ADD R11<<1, R1, R15
|
||||
MOVH (R15), R13
|
||||
JMP spread_inner_loop_condition
|
||||
|
||||
spread_inner_loop:
|
||||
ADD R10<<3, R5, R15
|
||||
MOVB R11, 1(R15)
|
||||
|
||||
adjust_position:
|
||||
ADD R8, R10, R10
|
||||
AND R9, R10, R10
|
||||
CMP R7, R10
|
||||
BGT adjust_position
|
||||
ADD $1, R12, R12
|
||||
|
||||
spread_inner_loop_condition:
|
||||
CMP R13, R12
|
||||
BLT spread_inner_loop
|
||||
ADD $1, R11, R11
|
||||
|
||||
spread_main_loop_condition:
|
||||
CMP R6, R11
|
||||
BLT spread_main_loop
|
||||
TST R10, R10
|
||||
BEQ spread_check_ok
|
||||
MOVD ctx+8(FP), R0
|
||||
MOVD R10, 24(R0)
|
||||
MOVD $+1, R16
|
||||
MOVD R16, ret+16(FP)
|
||||
RET
|
||||
|
||||
spread_check_ok:
|
||||
// Build Decoding table
|
||||
MOVD $0, R6
|
||||
|
||||
build_table_main_table:
|
||||
ADD R6<<3, R5, R15
|
||||
MOVBU 1(R15), R1
|
||||
ADD R1<<1, R3, R15
|
||||
MOVHU (R15), R7
|
||||
ADD $1, R7, R8
|
||||
ADD R1<<1, R3, R15
|
||||
MOVH R8, (R15)
|
||||
MOVD R7, R8
|
||||
CLZ R8, R16
|
||||
MOVD $63, R8
|
||||
SUB R16, R8, R8
|
||||
MOVD R2, R1
|
||||
SUB R8, R1, R1
|
||||
LSL R1, R7, R7
|
||||
SUB R0, R7, R7
|
||||
ADD R6<<3, R5, R15
|
||||
MOVB R1, (R15)
|
||||
ADD R6<<3, R5, R15
|
||||
MOVH R7, 2(R15)
|
||||
CMP R0, R7
|
||||
BLE build_table_check1_ok
|
||||
MOVD ctx+8(FP), R1
|
||||
MOVD R7, 24(R1)
|
||||
MOVD R0, 32(R1)
|
||||
MOVD $+2, R16
|
||||
MOVD R16, ret+16(FP)
|
||||
RET
|
||||
|
||||
build_table_check1_ok:
|
||||
AND $0xff, R1, R15
|
||||
AND $0xff, R1, R16
|
||||
TST R16, R15
|
||||
BNE build_table_check2_ok
|
||||
AND $0xffff, R7, R15
|
||||
AND $0xffff, R6, R16
|
||||
CMP R16, R15
|
||||
BNE build_table_check2_ok
|
||||
MOVD ctx+8(FP), R0
|
||||
MOVD R7, 24(R0)
|
||||
MOVD R6, 32(R0)
|
||||
MOVD $+3, R16
|
||||
MOVD R16, ret+16(FP)
|
||||
RET
|
||||
|
||||
build_table_check2_ok:
|
||||
ADD $1, R6, R6
|
||||
CMP R0, R6
|
||||
BLT build_table_main_table
|
||||
MOVD $+0, R16
|
||||
MOVD R16, ret+16(FP)
|
||||
RET
|
||||
Generated
Vendored
+6
-2
@@ -1,4 +1,4 @@
|
||||
//go:build amd64 && !appengine && !noasm && gc
|
||||
//go:build (amd64 || arm64) && !appengine && !noasm && gc
|
||||
|
||||
package zstd
|
||||
|
||||
@@ -6,6 +6,10 @@ import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// buildDtable_asm is generated by _generate/gen_fse.go and lowered to each
|
||||
// architecture (amd64 by goasm, arm64 by the avo arm64 lowering printer). The
|
||||
// Go side is identical across architectures, so it lives here.
|
||||
|
||||
type buildDtableAsmContext struct {
|
||||
// inputs
|
||||
stateTable *uint16
|
||||
@@ -18,7 +22,7 @@ type buildDtableAsmContext struct {
|
||||
errParam2 uint64
|
||||
}
|
||||
|
||||
// buildDtable_asm is an x86 assembly implementation of fseDecoder.buildDtable.
|
||||
// buildDtable_asm is an assembly implementation of fseDecoder.buildDtable.
|
||||
// Function returns non-zero exit code on error.
|
||||
//
|
||||
//go:noescape
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
//go:build !amd64 || appengine || !gc || noasm
|
||||
//go:build (!amd64 && !arm64) || appengine || !gc || noasm
|
||||
|
||||
package zstd
|
||||
|
||||
|
||||
Loaded 100 of 323 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user