Compare commits
167 Commits
9153dc4c89
...
908641234a
| Author | SHA1 | Date | |
|---|---|---|---|
| 908641234a | |||
| 5a821ac520 | |||
| 4128071070 | |||
| 0a74d2f25d | |||
| 7789297065 | |||
| 17628e554c | |||
| 8ec80c9828 | |||
| e83e911b2f | |||
| 6b00152847 | |||
| 9f32dfa7ba | |||
| 0cbfc046c7 | |||
| d02016c5fd | |||
| 9425a5c82f | |||
| 244ae1a162 | |||
| 8af99615c4 | |||
| cc4e857090 | |||
| ae2cb3c772 | |||
| fe6811f824 | |||
| 77bd87b4d1 | |||
| 7964a8ce43 | |||
| 09af56b342 | |||
| 6aa6b2c471 | |||
| a51a53db97 | |||
| 4ea2513b62 | |||
| b419498d9c | |||
| 636b7e28d8 | |||
| 015ed81e05 | |||
| 2f802866f9 | |||
| bea265cf26 | |||
| dcb9cf3d0a | |||
| f1618ee59b | |||
| 09044ef7a3 | |||
| 3c880378c9 | |||
| c388ade7f0 | |||
| 7ec875a49e | |||
| 4bc71adc19 | |||
| 4221a1b803 | |||
| 0c7d243d97 | |||
| 089ca8ae41 | |||
| de3c3f715b | |||
| 2128a95450 | |||
| 692e0f0789 | |||
| e646b8ebac | |||
| b5bed248d1 | |||
| 1cfc503bcd | |||
| 7327f0cf33 | |||
| c220a61ef4 | |||
| b2ed234d74 | |||
| 7b3f4d62b1 | |||
| 667a765070 | |||
| 61d2ca3e60 | |||
| 6d724ba6e0 | |||
| 71ea799e45 | |||
| ed076328cb | |||
| 13bc3a12c0 | |||
| 3a9a341527 | |||
| 2d4d830203 | |||
| be6671b2eb | |||
| 8d30cb57e2 | |||
| 507ecb264b | |||
| 07471c94d1 | |||
| 29b755243c | |||
| c8b0c5884d | |||
| 1fa662bb92 | |||
| 25d0026686 | |||
| a20ead67f1 | |||
| 2818208909 | |||
| 2e9cc27fc8 | |||
| 01dcb5aaf3 | |||
| 465cfb5293 | |||
| f58a65e4be | |||
| aa7be1edd1 | |||
| f868756721 | |||
| b66a4e32cc | |||
| 72df31e22d | |||
| 77639f94ce | |||
| bff6b4c3ab | |||
| aee115a99f | |||
| b81d92dbd2 | |||
| 98a0f5eb05 | |||
| 3350ae651d | |||
| 394a46f3a2 | |||
| 4624e84b50 | |||
| 21dd105d9a | |||
| 8d60b928fc | |||
| e7ae0bd716 | |||
| 4752ed84c7 | |||
| 5631d9b1c2 | |||
| b36b8e35af | |||
| 9ff3e5a895 | |||
| e5964e739e | |||
| 40d2849aa6 | |||
| f3ae7731d4 | |||
| 1c3a912532 | |||
| 2b61b2babf | |||
| d4b73af2e9 | |||
| b11731222f | |||
| f1873ad26d | |||
| aeb78e51a1 | |||
| 541aa6b1e1 | |||
| a9f259a1c7 | |||
| a2d4f12071 | |||
| 846432f4c8 | |||
| 167e23e9ba | |||
| ea2ef87d08 | |||
| e067bf1517 | |||
| 97b85334a9 | |||
| d4026ce60f | |||
| 40c631db32 | |||
| 095b0aca51 | |||
| a7dfbbb8ec | |||
| b65b7c5c56 | |||
| 4ebdfe4a1e | |||
| 19db35c48c | |||
| 1034dc9842 | |||
| 5bea84b94b | |||
| 7984e586a8 | |||
| b022e138d4 | |||
| db853850ab | |||
| 3d3d3b7355 | |||
| 3616b9d667 | |||
| efd9604aa7 | |||
| 1ab6bba61b | |||
| 9e6b4eeda8 | |||
| ea1a537a60 | |||
| 23a989118c | |||
| d0b2551e78 | |||
| b9b0e5ae80 | |||
| f7fbc6c2c3 | |||
| a286d28bf9 | |||
| 5cff808438 | |||
| 45e3ca6ea6 | |||
| 9c8557a124 | |||
| 8d7e3abbd6 | |||
| 9d50e20880 | |||
| fbf4f3e5fb | |||
| 820b9afe98 | |||
| b061673d9a | |||
| c9c47dc75c | |||
| cbb7c061a3 | |||
| caad25bb61 | |||
| 3b98059a8a | |||
| a8c236a54d | |||
| 81a5672498 | |||
| 1b5ea9a1fa | |||
| d438c6a96a | |||
| 6828ca1d4e | |||
| 88193b9396 | |||
| 3cedf032ca | |||
| 4396369bb9 | |||
| 4a4f8ad9db | |||
| 5a144e1342 | |||
| 24d72877e9 | |||
| c40f519b7b | |||
| b026c6844b | |||
| 21a5524fed | |||
| fe2d90641c | |||
| 8091a756e8 | |||
| 7542cd14e2 | |||
| 7da023f345 | |||
| a104de5b9f | |||
| 97c5f3fa02 | |||
| fccfa20653 | |||
| 29c6dacbfc | |||
| d33927718b | |||
| d153553d52 | |||
| db88253aac |
+34
-7
@@ -2,19 +2,26 @@
|
||||
|
||||
**Keep in mind that PocketBase is a non-commercial open source project, maintained entirely on volunteer basis (there is no company or dedicated team behind it), and there are no bounties!**
|
||||
|
||||
If you discover a security vulnerability within PocketBase, please send an e-mail to **support at pocketbase.io** or submit a private [GitHub Security advisory](https://github.com/pocketbase/pocketbase/security/advisories).
|
||||
If you want to responsibly report a security issue you'll have to reach out as a human to **support at pocketbase.io**.
|
||||
|
||||
I try to be as responsive as possible and usually address security reports within a day or two, but if you didn't receive a reply from me for more than 5 days it is very likely that your email was flagged and in that case please open a GitHub issue or discussion just mentioning that you found a vulnerability and want to report it so that I can see the notification and will try to contact you for more details.
|
||||
This means:
|
||||
- no overconfident and arrogant tone
|
||||
- no threatening deadlines
|
||||
- no requirement for me to login in your security platform just to read the report
|
||||
- no inflated severity (we can discuss the CVSS score after confirming the issue)
|
||||
- no LLMs usage as part of your report description or followup communication
|
||||
|
||||
In case the vulnerability is confirmed, within another couple days I'll try to submit a fix, GitHub security advisory and CVE with remediation steps and **minimal details** regarding the found exploit to minimize giving too much hints to malicious actors (you'll be credited both in the fix release notes and in the public report).
|
||||
Reports that don't follow the above will NOT be reviewed no matter of their validity _(you are of course free to publish whatever you want; see also [#7718](https://github.com/pocketbase/pocketbase/discussions/7718))_.
|
||||
|
||||
### Please:
|
||||
**Or in other words - a simple _"Hey I think I found a security issue when I do X"_ is enough.**
|
||||
|
||||
- DO NOT use LLM as part of your report or email communication - it is extremely frustrating to spend an hour or more reading a wall of generated text, writing an elaborate reply and then to receive another generic LLM prompt response in return.
|
||||
I try to be as responsive as possible and usually address security issues within couple days but if you didn't receive a reply from me for more than a week it is very likely that your email was flagged and in that case please open a GitHub issue or discussion just mentioning that you found a vulnerability and want to report it so that I can see the notification and will try to contact you for more details.
|
||||
|
||||
- DO NOT reserve and publish MITRE CVE number on your own _(I prefer to do it through the GitHub Security advisory)_ and try to communicate first privately the details to better understand how the code is being used and whether the supposed vulnerability can be actually exploited in any real practical scenarios. Otherwise you are risking needlessly causing scaremongering and annoyance for users that rely on security scanners as part of their CI/CD pipeline.
|
||||
In case the vulnerability is confirmed:
|
||||
|
||||
- Wait before publicly disclosing and sharing details about the found vulnerability, **ideally at least 5 days after the fix**, to make it harder to exploit and give enough time for users to patch their instances _(you are free to provide a PoC and as much details as you want in your own blog/gist/etc.)_.
|
||||
- I'll start working on a local fix.
|
||||
- Once the fix is implemented locally, I'll publish a pre-announcement with a scheduled release date _(and when possible an approximate release time)_.
|
||||
- After the release, I'll publish a GitHub security advisory and CVE with remediation steps and **minimal** details regarding the found exploit _(you are free to publish PoC and more details in your own blog, gist, etc. but it is advised to wait at least a week after the release to allow enough time for people to patch their instances before making it more publicly known)_.
|
||||
|
||||
### Below is a short list of previous reports that are NOT considered security issues:
|
||||
|
||||
@@ -84,6 +91,14 @@ In many places where applicable we've tried to minimize the impact by using cons
|
||||
If you think that there is a place where we can improve the handling without hurting too much the user experience, feel free to open a regular public issue and it will be considered.
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>Attack-vectors relying on social engineering</strong></summary>
|
||||
|
||||
Reports for attacks relying on various social engineering tactics _(e.g. tricking someone to click on a link)_ are valid concerns but usually out of the security scope of the project as there are a lot of cases where the APIs are deliberately designed for minimal friction.
|
||||
|
||||
If you have concerns for such attack, feel free to open a regular public issue and we can eventually try to reconsider adding extra guards when feasible _(or at least properly document the existing behavior)_.
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong><code>disintegration/imaging</code> CVE-2023-36308</strong></summary>
|
||||
|
||||
@@ -99,3 +114,15 @@ Third, even if that issue is still available, with PocketBase it would have been
|
||||
|
||||
In the future I may consider eventually replacing the library because it is no longer actively maintained but as of now it is working correctly and as expected for our use case and you can safely flag the security warning as false-positive.
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>JSVM "sandboxing"</strong></summary>
|
||||
|
||||
This is another very common report but **there is no such thing as JSVM "sandboxing" in PocketBase**.
|
||||
|
||||
The JS `pb_hooks` (or JSVM for short) are NOT supposed to run untrusted or client provided JavaScript code _(the same way you are not supposed to run untrusted code in your Node.js server)_.
|
||||
|
||||
Once interpreted the `pb_hooks` run as part of the same application process together with the rest of the Go code. There are no additional filesystem, network, memory, etc. restrictions. This means that it is OK for developers to be able to access environment variables, perform network calls to any URLs they want, invoke shell commands or even sleep/block the script execution.
|
||||
|
||||
So if you are security researcher and not sure if something is a security fault in the JS hooks, ask yourself - "Can I do the same when using PocketBase as Go framework?" and if the answer is "Yes" then it is not a security issue with the JSVM.
|
||||
</details>
|
||||
|
||||
@@ -28,7 +28,7 @@ jobs:
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version: '>=1.26.2'
|
||||
go-version: '>=1.26.5'
|
||||
|
||||
# This step usually is not needed because the /ui/dist is pregenerated locally
|
||||
# but its here to ensure that each release embeds the latest admin ui artifacts.
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ builds:
|
||||
main: ./examples/base
|
||||
binary: pocketbase
|
||||
ldflags:
|
||||
- -s -w -X github.com/pocketbase/pocketbase.Version={{ .Version }}
|
||||
- -s -w -X github.com/tabshift-gh/pocketbase.Version={{ .Version }}
|
||||
env:
|
||||
- CGO_ENABLED=0
|
||||
goos:
|
||||
|
||||
+194
@@ -1,3 +1,197 @@
|
||||
## v0.39.10
|
||||
|
||||
- Reverted the auto panic recover handling for the cli commands to preserve the old behavior and allow panic to force exit with non-zero code ([#7781](https://github.com/pocketbase/pocketbase/issues/7781)).
|
||||
_Proper command non-zero exit support will be available with the next v0.40/v0.41 release._
|
||||
|
||||
- Minor UI improvements (added placeholder loader for the logs chart, npm dev deps update, etc.).
|
||||
|
||||
- Updated `modernc.org/sqlite` to v1.55.0 (doc changes).
|
||||
|
||||
|
||||
## v0.39.9
|
||||
|
||||
- Fixed `Shift + Click` range bulk selection not working in Firefox ([#7771](https://github.com/pocketbase/pocketbase/issues/7771))
|
||||
|
||||
- Updated goja and its related dependencies _(fixes for TypedArray and regexp2 dep regression for the reported empty string match with lookahead patterns)_.
|
||||
|
||||
- Minor filter (fexpr) improvements _(optimization for large string literals and fix for control characters handling)_.
|
||||
|
||||
|
||||
## v0.39.8
|
||||
|
||||
- Properly reset JSVM global `$app` overwrite so that pooled executors always get a clean state.
|
||||
|
||||
- Minor UI improvements:
|
||||
- prevent resetting number inputs with leading 0 while still typing (normalized in `onchange`)
|
||||
- added support for `Shift + Click` range bulk selection ([#7759](https://github.com/pocketbase/pocketbase/issues/7759))
|
||||
|
||||
- Bumped `golang.org/x/*` indirect dependencies as there are some minor security fixes.
|
||||
|
||||
- Updated `modernc.org/sqlite` to v1.54.0 ([SQLite 3.53.3](https://sqlite.org/src/timeline?from=version-3.53.2&to=version-3.53.3&to2=branch-3.53)).
|
||||
|
||||
|
||||
## v0.39.7
|
||||
|
||||
- Replaced `github.com/go-ozzo/ozzo-validation` with the fork `github.com/pocketbase/ozzo-validation` since the original library has recently changed ownership and the new maintainer cannot be trusted.
|
||||
_There are plans to create eventually a new validation library from scratch more suited for our needs in PocketBase because ozzo-validation is known to have some minor performance and obscure regex issues, but until then we'll stick with the fork (and if you use `ozzo-validation` in your own Go code, I'd suggest to swap the imports with the fork)_.
|
||||
|
||||
- Fixed missing import collection `fields` property access ([#7760](https://github.com/pocketbase/pocketbase/issues/7760)).
|
||||
|
||||
- Fixed View collection `*` validator and added more friendly error messages ([#7761](https://github.com/pocketbase/pocketbase/issues/7761)).
|
||||
|
||||
- ⚠️ Security fix for unhandled panic in internal worker goroutines ([#7762](https://github.com/pocketbase/pocketbase/discussions/7762)).
|
||||
_To prevent this from showing again, all existing internal worker functions were wrapped with [`routine.SafeWrap(f)`](https://pkg.go.dev/github.com/pocketbase/pocketbase/tools/routine#SafeWrap) (auto recovers and returns any eventual panic as regular error)._
|
||||
|
||||
|
||||
## v0.39.6
|
||||
|
||||
- Added `Cc` and `Bcc` recipients to the dev `sendmail` command for consistency with the SMTP mailer.
|
||||
|
||||
- Added extra hardening options to the Microsoft OAuth2 provider allowing developers to specify the preferred safe email extraction method.
|
||||
|
||||
- Updated goja and the related `golang.org/x/*` dependencies _(`WeakMap` regression fixes)_.
|
||||
|
||||
- Bumped the min Go GitHub action version to 1.26.5 as it includes some [minor security fixes](https://github.com/golang/go/issues?q=milestone%3AGo1.26.5).
|
||||
|
||||
|
||||
## v0.39.5
|
||||
|
||||
- Limit with ellipsis long `url` field values.
|
||||
|
||||
- Readded the "fullscreen" `editor` field option and preloaded the TinyMCE component for slightly faster initial rendering ([#7746](https://github.com/pocketbase/pocketbase/issues/7746)).
|
||||
|
||||
- Updated goja (`TypedArray` fixes).
|
||||
|
||||
|
||||
## v0.39.4
|
||||
|
||||
- Removed `redirectURL` required validator from the code->token exchange endpoint (aka. `authWithOAuth2Code()`) ([#7734](https://github.com/pocketbase/pocketbase/issues/7734)).
|
||||
_Note that OAuth2 providers have their own validations and whether it is allowed to be empty or not could depend on the configured OAuth2 app (in most cases it is required and the redirect address must match with the initial value submitted with the authorization request)._
|
||||
|
||||
- Enabled sorting by the first _implicit_ presentable relation field ([#7735](https://github.com/pocketbase/pocketbase/discussions/7735)).
|
||||
|
||||
- Other minor UI fixes (tooltip clear on hovered element removal, optional before element sortable fix, etc.).
|
||||
|
||||
- Updated goja and the related `golang.org/x/*` dependencies (regex support improvements).
|
||||
|
||||
|
||||
## v0.39.3
|
||||
|
||||
- Fixed JS error on `file` settings `maxSelect` change ([#7731](https://github.com/pocketbase/pocketbase/issues/7731)).
|
||||
|
||||
- Apply the `Ctrl+S` record panel save shortcut only if it is the current top open modal.
|
||||
|
||||
- Fixed `number` settings validator to not ignore 0 `max` value.
|
||||
|
||||
- Normalized field settings validation error messages and tooltips.
|
||||
|
||||
|
||||
## v0.39.2
|
||||
|
||||
- Fixed records list UI sorting ([#7724](https://github.com/pocketbase/pocketbase/issues/7724)).
|
||||
|
||||
- Don't clear the date input on invalid value while still typing ([#7726](https://github.com/pocketbase/pocketbase/issues/7726)).
|
||||
|
||||
- Return `filepath.SkipDir` in the `pb_hooks` dirs watcher to avoid unnecessary iterating over `node_modules` and `.*` prefixed hidden dirs (`.DS_Store`, `.git`, etc.).
|
||||
|
||||
- Show the "Affected rows" SQL console message only if non-empty to avoid ambiguity with drivers that don't support returning the affected rows count.
|
||||
|
||||
- Updated `modernc.org/sqlite` to v1.52.0 ([SQLite 3.53.2](https://sqlite.org/src/timeline?from=version-3.53.0&to=version-3.53.2&to2=branch-3.53&y=ci)).
|
||||
|
||||
|
||||
## v0.39.1
|
||||
|
||||
- Fixed multiple select options wrapping ([#7720](https://github.com/pocketbase/pocketbase/issues/7720)).
|
||||
|
||||
- Return the hidden record data fields for superusers realtime subscribers ([#7721](https://github.com/pocketbase/pocketbase/issues/7721)).
|
||||
|
||||
- Added default panic-recover handling for the cron jobs to avoid terminating the server on panic.
|
||||
|
||||
- Bumped the min Go GitHub action version to 1.26.4 as it includes some [minor security fixes](https://github.com/golang/go/issues?q=milestone%3AGo1.26.4).
|
||||
|
||||
|
||||
## v0.39.0
|
||||
|
||||
- Added new "SQL console" section under _Settings > Debug_ allowing executing any raw SQL query from the UI ([#2236](https://github.com/pocketbase/pocketbase/issues/2236); [#7638](https://github.com/pocketbase/pocketbase/discussions/7638)).
|
||||
_Note that this is intended for one-off analytic queries, the occasional `VACUUM`/`PRAGMA optimize` or debug purposes and not as the primary interface for interacting with your PocketBase data because it can break your application if not used with proper care!_
|
||||
|
||||
- Send system email alerts to superusers in case of an error with the automated backups ([#7698](https://github.com/pocketbase/pocketbase/issues/7698)).
|
||||
|
||||
- Various minor improvements and fixes:
|
||||
- fixed logs bulk selection export error
|
||||
- optimized logs and records list rendering
|
||||
- allowed word breaking in labels
|
||||
- text contrast improvements
|
||||
- registered missing `oidc2` and `oidc3` option fields
|
||||
- updated default email template texts for consistency
|
||||
- updated `modernc.org/sqlite` to v1.51.0
|
||||
- etc.
|
||||
|
||||
|
||||
## v0.38.2
|
||||
|
||||
- Added `RealtimeConnectRequestEvent.MaxTimeout` field to specify the absolute max duration a realtime connection can remain open (default to 30mins).
|
||||
_This is in addition to the `IdeTimeout` of 5mins in order to prevent misuse and to allow the GC to run more regularly._
|
||||
|
||||
- Added extra checks for the connected user IP in the realtime APIs to prevent bruteforce guest subscription update attempts and to serve as an extra protection for the "all-in-one" OAuth2 realtime handler.
|
||||
|
||||
- Don't reset the records list pagination on record update ([#7694](https://github.com/pocketbase/pocketbase/issues/7694)).
|
||||
|
||||
- Updated all `golang.org/x/` packages to cover the recent [security fixes](https://groups.google.com/g/golang-announce/c/PdiGK3xulk4) _(none of them should be a critical issue in PocketBase but nonetheless it is advised to update)_.
|
||||
|
||||
|
||||
## v0.38.1
|
||||
|
||||
- Silenced the superuser IPs confirmation if there is no change.
|
||||
|
||||
- Updated the _experimental_ UI extensions APIs to allow top-level `await` in the initialization script.
|
||||
|
||||
- Force unset the auth state of existing realtime connections on user password, collection secret, etc. changes.
|
||||
_This is not strictly necessary because the realtime connections have short-lived idle timeout by design but nonetheless it was implemented to minimize the attack vectors._
|
||||
|
||||
- Added error marker for each collection tab and fixed the styles of the raw errors tooltip.
|
||||
|
||||
- Fixed indexes collection update error ([#7689](https://github.com/pocketbase/pocketbase/issues/7689)).
|
||||
_⚠️ The fix comes with a system migration that resaves all collections with indexes to ensure that all indexes are normalized and available in the `Collection.Indexes` field (it will also include indexes created manually via the sqlite3 cli or other external tool)._
|
||||
_If you are using a test `pb_data` for your Go automation tests you may want to apply the migration to it too so that it runs only once and not for each execution of your tests, aka. you could run once `go run main.go migrate up --dir="/path/to/test_pb_data"`._
|
||||
|
||||
- Updated `modernc.org/sqlite` to v1.50.1 (SQLite 3.53.1).
|
||||
|
||||
- Other minor fixes (_updated API preview examples, fixed code comment typos, etc._).
|
||||
|
||||
|
||||
## v0.38.0
|
||||
|
||||
- Fixed UI logs pagination when no custom range is specified.
|
||||
|
||||
- Fixed default CSP not allowing audio/video previews ([#7677](https://github.com/pocketbase/pocketbase/issues/7677)).
|
||||
|
||||
- Serve fixed `Content-Type` for `.xlsx`, `.docx` and `.pptx` files to allow previews on iOS ([#7467](https://github.com/pocketbase/pocketbase/discussions/7467)).
|
||||
|
||||
- Changed settings app URL input to `type="text"` for compatibility with earlier versions ([#7681](https://github.com/pocketbase/pocketbase/issues/7681)).
|
||||
|
||||
- Added an internal watcher to sync various runtime states between multiple PocketBase processes (e.g. memory store) using the same `pb_data`.
|
||||
_This is helpful in case for example a separate PocketBase console command change the collections or application settings while the server is still running._
|
||||
_The watcher is debounced and implemented by watching the special `pb_data/.notify` dir as a workaround to avoid depending on OS and SQLite driver specific APIs._
|
||||
|
||||
- Added new [Superuser IPs/CIDR subnets whitelist setting](https://pocketbase.io/docs/going-to-production/#limit-superusers-to-specific-ipssubnets).
|
||||
The optional setting can be changed from the UI under _Dasboard > Settings > Application > Superuser IPs_.
|
||||
To avoid lockout in case your superuser IP change, the ips whitelist can be updated also via the `superuser ips` console command:
|
||||
```sh
|
||||
# note: --dir is optional and defaults to pb_data next to the executable
|
||||
|
||||
# clear whitelisted IPs
|
||||
./pocketbase superuser ips --dir=/custom/path/to/pb_data
|
||||
|
||||
# OR change the whitelisted IPs to 127.0.0.1 and 10.0.0.0 (replace with your real IP(s))
|
||||
./pocketbase superuser ips 127.0.0.1 10.0.0.0 --dir=/custom/path/to/pb_data
|
||||
```
|
||||
|
||||
- Added rate limit option to exclude IPs/CIDR subnets ([#6410](https://github.com/pocketbase/pocketbase/issues/6410)).
|
||||
|
||||
- Bumped min Go GitHub action version to 1.26.3 because it comes with some [minor bug and security fixes](https://github.com/golang/go/issues?q=milestone%3AGo1.26.3).
|
||||
|
||||
|
||||
## v0.37.5
|
||||
|
||||
- Fixed password fields not being detected as changed ([#7670](https://github.com/pocketbase/pocketbase/issues/7670)).
|
||||
|
||||
@@ -2,6 +2,57 @@
|
||||
> For the most recent versions, please refer to [CHANGELOG.md](./CHANGELOG.md)
|
||||
---
|
||||
|
||||
## v0.22.51
|
||||
|
||||
- (_Backported from v0.39.10_) Reverted the auto panic recover handling for the cli commands to preserve the old behavior and allow panic to force exit with non-zero code ([#7781](https://github.com/pocketbase/pocketbase/issues/7781)).
|
||||
|
||||
|
||||
## v0.22.50
|
||||
|
||||
- (_Backported from v0.39.9_) Bumped goja, fexpr and their related deps.
|
||||
|
||||
|
||||
## v0.22.49
|
||||
|
||||
- (_Backported from v0.39.8_) Bumped `golang.org/x/*` indirect dependencies as there are some minor security fixes.
|
||||
|
||||
- (_Backported from v0.39.8_) Updated `modernc.org/sqlite` to v1.54.0 ([SQLite 3.53.3](https://sqlite.org/src/timeline?from=version-3.53.2&to=version-3.53.3&to2=branch-3.53)).
|
||||
|
||||
|
||||
## v0.22.48
|
||||
|
||||
- (_Backported from v0.39.7_) Replaced `github.com/go-ozzo/ozzo-validation` with the fork `github.com/pocketbase/ozzo-validation` since the original library has recently changed ownership and the new maintainer cannot be trusted.
|
||||
|
||||
- (_Backported from v0.39.7_) Fixed View collection `*` validator and added more friendly error messages ([#7761](https://github.com/pocketbase/pocketbase/issues/7761)).
|
||||
|
||||
- (_Backported from v0.39.7_) ⚠️ Security fix for unhandled panic in internal worker goroutines ([#7762](https://github.com/pocketbase/pocketbase/discussions/7762)).
|
||||
|
||||
|
||||
## v0.22.47
|
||||
|
||||
- (_Backported from v0.39.6_) Bumped the min Go GitHub action version to 1.26.5 as it includes some [minor security fixes](https://github.com/golang/go/issues?q=milestone%3AGo1.26.5).
|
||||
|
||||
|
||||
## v0.22.46
|
||||
|
||||
- (_Backported from v0.39.1_) Bumped the min Go GitHub action version to 1.26.4 as it includes some [minor security fixes](https://github.com/golang/go/issues?q=milestone%3AGo1.26.4).
|
||||
|
||||
|
||||
## v0.22.45
|
||||
|
||||
- (_Backported from v0.38.2_) Updated all `golang.org/x/` packages to cover the recent [security fixes](https://groups.google.com/g/golang-announce/c/PdiGK3xulk4) _(none of them should be a critical issue in PocketBase but nonetheless it is advised to update)_.
|
||||
|
||||
|
||||
## v0.22.44
|
||||
|
||||
- (_Backported from v0.38.1_) Force unset the auth state of existing realtime connections on user tokenKey change.
|
||||
|
||||
|
||||
## v0.22.43
|
||||
|
||||
- (_Backported from v0.38.0_) Bumped min Go GitHub action version to 1.26.3 because it comes with some [minor bug and security fixes](https://github.com/golang/go/issues?q=milestone%3AGo1.26.3).
|
||||
|
||||
|
||||
## v0.22.42
|
||||
|
||||
- (_Backported from v0.37.4_) Adjusted Bitbucket, GitHub, GitLab and Gitea/Forgejo OAuth2 providers to better reflect recent API updates and doc references.
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/pocketbase/pocketbase/actions/workflows/release.yaml" target="_blank" rel="noopener"><img src="https://github.com/pocketbase/pocketbase/actions/workflows/release.yaml/badge.svg" alt="build" /></a>
|
||||
<a href="https://github.com/pocketbase/pocketbase/releases" target="_blank" rel="noopener"><img src="https://img.shields.io/github/release/pocketbase/pocketbase.svg" alt="Latest releases" /></a>
|
||||
<a href="https://pkg.go.dev/github.com/pocketbase/pocketbase" target="_blank" rel="noopener"><img src="https://godoc.org/github.com/pocketbase/pocketbase?status.svg" alt="Go package documentation" /></a>
|
||||
<a href="https://github.com/pocketbase/pocketbase/actions/workflows/release.yaml" target="_blank" rel="noopener"><img src="https://github.com/tabshift-gh/pocketbase/actions/workflows/release.yaml/badge.svg" alt="build" /></a>
|
||||
<a href="https://github.com/tabshift-gh/pocketbase/releases" target="_blank" rel="noopener"><img src="https://img.shields.io/github/release/tabshift-gh/pocketbase.svg" alt="Latest releases" /></a>
|
||||
<a href="https://pkg.go.dev/github.com/pocketbase/pocketbase" target="_blank" rel="noopener"><img src="https://godoc.org/github.com/tabshift-gh/pocketbase?status.svg" alt="Go package documentation" /></a>
|
||||
</p>
|
||||
|
||||
[PocketBase](https://pocketbase.io) is an open source Go backend that includes:
|
||||
@@ -17,6 +17,12 @@
|
||||
- convenient **Admin dashboard UI**
|
||||
- and simple **REST-ish API**
|
||||
|
||||
> [!NOTE]
|
||||
> This is a fork of the great [pocketbase/pocketbase][] repository adapted for
|
||||
> Tabshift's purposes.
|
||||
|
||||
[pocketbase/pocketbase]: https://github.com/pocketbase/pocketbase
|
||||
|
||||
**For documentation and examples, please visit https://pocketbase.io/docs.**
|
||||
|
||||
> [!WARNING]
|
||||
@@ -32,7 +38,6 @@ The easiest way to interact with the PocketBase Web APIs is to use one of the of
|
||||
|
||||
You could also check the recommendations in https://pocketbase.io/docs/how-to-use/.
|
||||
|
||||
|
||||
## Overview
|
||||
|
||||
### Use as standalone app
|
||||
@@ -52,6 +57,7 @@ Here is a minimal example:
|
||||
0. [Install Go 1.25+](https://go.dev/doc/install) (_if you haven't already_)
|
||||
|
||||
1. Create a new project directory with the following `main.go` file inside it:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package apis
|
||||
|
||||
import "github.com/pocketbase/pocketbase/tools/router"
|
||||
import "github.com/tabshift-gh/pocketbase/tools/router"
|
||||
|
||||
// ApiError aliases to minimize the breaking changes with earlier versions
|
||||
// and for consistency with the JSVM binds.
|
||||
|
||||
+11
-6
@@ -6,10 +6,10 @@ import (
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/router"
|
||||
"github.com/pocketbase/pocketbase/tools/routine"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/router"
|
||||
"github.com/tabshift-gh/pocketbase/tools/routine"
|
||||
"github.com/tabshift-gh/pocketbase/tools/types"
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
|
||||
@@ -70,8 +70,10 @@ func backupDownload(e *core.RequestEvent) error {
|
||||
return e.ForbiddenError("Insufficient permissions to access the resource.", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
|
||||
defer cancel()
|
||||
allowedIPs := e.App.Settings().SuperuserIPs
|
||||
if len(allowedIPs) > 0 && !isIPInList(allowedIPs, e.RealIP()) {
|
||||
return e.ForbiddenError("Insufficient permissions to access the resource.", nil)
|
||||
}
|
||||
|
||||
fsys, err := e.App.NewBackupsFilesystem()
|
||||
if err != nil {
|
||||
@@ -79,6 +81,9 @@ func backupDownload(e *core.RequestEvent) error {
|
||||
}
|
||||
defer fsys.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
fsys.SetContext(ctx)
|
||||
|
||||
key := e.Request.PathValue("key")
|
||||
|
||||
@@ -5,8 +5,8 @@ import (
|
||||
"net/http"
|
||||
"regexp"
|
||||
|
||||
validation "github.com/go-ozzo/ozzo-validation/v4"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
validation "github.com/pocketbase/ozzo-validation/v4"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
)
|
||||
|
||||
func backupCreate(e *core.RequestEvent) error {
|
||||
|
||||
+56
-4
@@ -10,10 +10,10 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/apis"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/pocketbase/pocketbase/tools/filesystem/blob"
|
||||
"github.com/tabshift-gh/pocketbase/apis"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/tools/filesystem/blob"
|
||||
)
|
||||
|
||||
func TestBackupsList(t *testing.T) {
|
||||
@@ -528,6 +528,58 @@ func TestBackupsDownload(t *testing.T) {
|
||||
},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
},
|
||||
{
|
||||
Name: "with valid superuser file token AND whitelisted IP",
|
||||
Method: http.MethodGet,
|
||||
URL: "/api/backups/test1.zip?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsImV4cCI6MjUyNDYwNDQ2MSwidHlwZSI6ImZpbGUiLCJjb2xsZWN0aW9uSWQiOiJwYmNfMzE0MjYzNTgyMyJ9.Lupz541xRvrktwkrl55p5pPCF77T69ZRsohsIcb2dxc",
|
||||
Headers: map[string]string{"x-test-ip": "127.0.0.1"},
|
||||
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
|
||||
if err := createTestBackups(app); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
app.Settings().TrustedProxy = core.TrustedProxyConfig{
|
||||
Headers: []string{"x-test-ip"},
|
||||
}
|
||||
|
||||
app.Settings().SuperuserIPs = []string{"127.0.0.1"}
|
||||
|
||||
if err := app.Save(app.Settings()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
},
|
||||
ExpectedStatus: 200,
|
||||
ExpectedContent: []string{
|
||||
"storage/",
|
||||
"data.db",
|
||||
"auxiliary.db",
|
||||
},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
},
|
||||
{
|
||||
Name: "with valid superuser file token BUT non-whitelisted IP",
|
||||
Method: http.MethodGet,
|
||||
URL: "/api/backups/test1.zip?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsImV4cCI6MjUyNDYwNDQ2MSwidHlwZSI6ImZpbGUiLCJjb2xsZWN0aW9uSWQiOiJwYmNfMzE0MjYzNTgyMyJ9.Lupz541xRvrktwkrl55p5pPCF77T69ZRsohsIcb2dxc",
|
||||
Headers: map[string]string{"x-test-ip": "127.0.0.1"},
|
||||
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
|
||||
if err := createTestBackups(app); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
app.Settings().TrustedProxy = core.TrustedProxyConfig{
|
||||
Headers: []string{"x-test-ip"},
|
||||
}
|
||||
|
||||
app.Settings().SuperuserIPs = []string{"0.0.0.0"}
|
||||
|
||||
if err := app.Save(app.Settings()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
},
|
||||
ExpectedStatus: 403,
|
||||
ExpectedContent: []string{`"data":{}`},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
},
|
||||
}
|
||||
|
||||
for _, scenario := range scenarios {
|
||||
|
||||
@@ -3,10 +3,10 @@ package apis
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
validation "github.com/go-ozzo/ozzo-validation/v4"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/core/validators"
|
||||
"github.com/pocketbase/pocketbase/tools/filesystem"
|
||||
validation "github.com/pocketbase/ozzo-validation/v4"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/core/validators"
|
||||
"github.com/tabshift-gh/pocketbase/tools/filesystem"
|
||||
)
|
||||
|
||||
func backupUpload(e *core.RequestEvent) error {
|
||||
|
||||
+4
-2
@@ -8,8 +8,8 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/router"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/router"
|
||||
)
|
||||
|
||||
// StaticWildcardParam is the name of Static handler wildcard parameter.
|
||||
@@ -31,6 +31,7 @@ func NewRouter(app core.App) (*router.Router[*core.RequestEvent], error) {
|
||||
pbRouter.Bind(panicRecover())
|
||||
pbRouter.Bind(rateLimit())
|
||||
pbRouter.Bind(loadAuthToken())
|
||||
pbRouter.Bind(superuserIPsWhitelist())
|
||||
pbRouter.Bind(securityHeaders())
|
||||
pbRouter.Bind(BodyLimit(DefaultMaxBodySize))
|
||||
|
||||
@@ -47,6 +48,7 @@ func NewRouter(app core.App) (*router.Router[*core.RequestEvent], error) {
|
||||
bindBatchApi(app, apiGroup)
|
||||
bindRealtimeApi(app, apiGroup)
|
||||
bindHealthApi(app, apiGroup)
|
||||
bindSQLApi(app, apiGroup)
|
||||
|
||||
// UI routes
|
||||
bindUIExtensions(app)
|
||||
|
||||
+4
-4
@@ -8,10 +8,10 @@ import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/apis"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/pocketbase/pocketbase/tools/router"
|
||||
"github.com/tabshift-gh/pocketbase/apis"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/tools/router"
|
||||
)
|
||||
|
||||
func TestWrapStdHandler(t *testing.T) {
|
||||
|
||||
+8
-7
@@ -14,11 +14,12 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
validation "github.com/go-ozzo/ozzo-validation/v4"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/filesystem"
|
||||
"github.com/pocketbase/pocketbase/tools/router"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
validation "github.com/pocketbase/ozzo-validation/v4"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/filesystem"
|
||||
"github.com/tabshift-gh/pocketbase/tools/router"
|
||||
"github.com/tabshift-gh/pocketbase/tools/routine"
|
||||
"github.com/tabshift-gh/pocketbase/tools/types"
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
|
||||
@@ -195,7 +196,7 @@ func (p *batchProcessor) Process(batch []*core.InternalRequest, timeout time.Dur
|
||||
p.stopCh <- struct{}{}
|
||||
}()
|
||||
|
||||
go func() {
|
||||
routine.FireAndForget(func() {
|
||||
err := p.process(txApp, batch, 0)
|
||||
|
||||
if err != nil {
|
||||
@@ -216,7 +217,7 @@ func (p *batchProcessor) Process(batch []*core.InternalRequest, timeout time.Dur
|
||||
}
|
||||
|
||||
p.errCh <- err
|
||||
}()
|
||||
})
|
||||
|
||||
select {
|
||||
case responseErr := <-p.errCh:
|
||||
|
||||
+68
-4
@@ -6,9 +6,9 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/pocketbase/pocketbase/tools/router"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/tools/router"
|
||||
)
|
||||
|
||||
func TestBatchRequest(t *testing.T) {
|
||||
@@ -224,7 +224,7 @@ func TestBatchRequest(t *testing.T) {
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "mixed create/update/delete (rules failure)",
|
||||
Name: "mixed create/update/delete (non-superuser rule failure)",
|
||||
Method: http.MethodPost,
|
||||
URL: "/api/batch",
|
||||
Body: strings.NewReader(`{
|
||||
@@ -284,6 +284,70 @@ func TestBatchRequest(t *testing.T) {
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "mixed create/update/delete (superuser rule failure)",
|
||||
Method: http.MethodPost,
|
||||
URL: "/api/batch",
|
||||
Headers: map[string]string{
|
||||
// test@example.com, clients
|
||||
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6ImdrMzkwcWVnczR5NDd3biIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoidjg1MXE0cjc5MHJoa25sIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.0ONnm_BsvPRZyDNT31GN1CKUB6uQRxvVvQ-Wc9AZfG0",
|
||||
},
|
||||
Body: strings.NewReader(`{
|
||||
"requests": [
|
||||
{"method":"DELETE", "url":"/api/collections/demo2/records/achvryl401bhse3", "headers": {"Authorization": "ignored"}},
|
||||
{"method":"PATCH", "url":"/api/collections/demo3/records/1tmknxy2868d869", "body": {"title": "batch_update"}, "headers": {"Authorization": "ignored"}},
|
||||
{"method":"POST", "url":"/api/collections/_superusers/records", "body": {"email":"test_batch@example.com","password":"1234567890"}}
|
||||
]
|
||||
}`),
|
||||
ExpectedStatus: 400,
|
||||
ExpectedContent: []string{
|
||||
`"data":{`,
|
||||
`"requests":{`,
|
||||
`"2":{"code":"batch_request_failed"`,
|
||||
`403`,
|
||||
},
|
||||
NotExpectedContent: []string{
|
||||
`"0":`,
|
||||
`"1":`,
|
||||
},
|
||||
ExpectedEvents: map[string]int{
|
||||
"*": 0,
|
||||
"OnBatchRequest": 1,
|
||||
"OnModelUpdate": 1,
|
||||
"OnModelUpdateExecute": 1,
|
||||
"OnModelAfterUpdateError": 1,
|
||||
"OnModelDelete": 1,
|
||||
"OnModelDeleteExecute": 1,
|
||||
"OnModelAfterDeleteError": 1,
|
||||
"OnModelValidate": 1,
|
||||
"OnRecordUpdateRequest": 1,
|
||||
"OnRecordUpdate": 1,
|
||||
"OnRecordUpdateExecute": 1,
|
||||
"OnRecordAfterUpdateError": 1,
|
||||
"OnRecordDeleteRequest": 1,
|
||||
"OnRecordDelete": 1,
|
||||
"OnRecordDeleteExecute": 1,
|
||||
"OnRecordAfterDeleteError": 1,
|
||||
"OnRecordEnrich": 1,
|
||||
"OnRecordValidate": 1,
|
||||
},
|
||||
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
|
||||
_, err = app.FindRecordById("demo2", "achvryl401bhse3")
|
||||
if err != nil {
|
||||
t.Fatal("Expected record to not be deleted")
|
||||
}
|
||||
|
||||
_, err = app.FindFirstRecordByFilter("demo3", `title="batch_update"`)
|
||||
if err == nil {
|
||||
t.Fatal("Expected record to not be updated")
|
||||
}
|
||||
|
||||
_, err = app.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test_batch@example.com")
|
||||
if err == nil {
|
||||
t.Fatal("Expected superuser to not be created")
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "mixed create/update/delete (rules success)",
|
||||
Method: http.MethodPost,
|
||||
|
||||
+6
-6
@@ -6,12 +6,12 @@ import (
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
validation "github.com/go-ozzo/ozzo-validation/v4"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/auth"
|
||||
"github.com/pocketbase/pocketbase/tools/router"
|
||||
"github.com/pocketbase/pocketbase/tools/search"
|
||||
"github.com/pocketbase/pocketbase/tools/security"
|
||||
validation "github.com/pocketbase/ozzo-validation/v4"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/auth"
|
||||
"github.com/tabshift-gh/pocketbase/tools/router"
|
||||
"github.com/tabshift-gh/pocketbase/tools/search"
|
||||
"github.com/tabshift-gh/pocketbase/tools/security"
|
||||
)
|
||||
|
||||
// bindCollectionApi registers the collection api endpoints and the corresponding handlers.
|
||||
|
||||
@@ -4,8 +4,8 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
validation "github.com/go-ozzo/ozzo-validation/v4"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
validation "github.com/pocketbase/ozzo-validation/v4"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
)
|
||||
|
||||
func collectionsImport(e *core.RequestEvent) error {
|
||||
|
||||
@@ -6,8 +6,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
)
|
||||
|
||||
func TestCollectionsImport(t *testing.T) {
|
||||
|
||||
@@ -8,9 +8,9 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/pocketbase/pocketbase/tools/list"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/tools/list"
|
||||
)
|
||||
|
||||
func TestCollectionsList(t *testing.T) {
|
||||
|
||||
+4
-4
@@ -5,10 +5,10 @@ import (
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/cron"
|
||||
"github.com/pocketbase/pocketbase/tools/router"
|
||||
"github.com/pocketbase/pocketbase/tools/routine"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/cron"
|
||||
"github.com/tabshift-gh/pocketbase/tools/router"
|
||||
"github.com/tabshift-gh/pocketbase/tools/routine"
|
||||
)
|
||||
|
||||
// bindCronApi registers the crons api endpoint.
|
||||
|
||||
+2
-2
@@ -5,8 +5,8 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
|
||||
|
||||
+5
-4
@@ -8,9 +8,9 @@ import (
|
||||
"log/slog"
|
||||
"os"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/hook"
|
||||
"github.com/pocketbase/pocketbase/ui"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/hook"
|
||||
"github.com/tabshift-gh/pocketbase/ui"
|
||||
)
|
||||
|
||||
// bindUIExtensions binds the superuser UI extensions routes to the ServeEvent.Router.
|
||||
@@ -81,7 +81,8 @@ func copyExtensionMainjs(buf *bytes.Buffer, ext core.UIExtension) error {
|
||||
defer f.Close()
|
||||
|
||||
// wrap in a self-executing function to avoid scope and concatenation issues
|
||||
_, _ = buf.WriteString("(function(){")
|
||||
// (the await/async is for top-level await)
|
||||
_, _ = buf.WriteString("await (async function(){")
|
||||
|
||||
_, err = io.Copy(buf, f)
|
||||
if err != nil {
|
||||
|
||||
@@ -5,9 +5,9 @@ import (
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/pocketbase/pocketbase/ui"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/ui"
|
||||
)
|
||||
|
||||
// note: don't run in parallel to avoid conflicts with the ui.DistDirFS nil test
|
||||
@@ -72,7 +72,7 @@ func TestUIExtensions_Mainjs(t *testing.T) {
|
||||
},
|
||||
AfterTestFunc: successAfterTestFunc,
|
||||
ExpectedStatus: 200,
|
||||
ExpectedContent: []string{"(function(){ext1_main})();(function(){ext3_main})();"},
|
||||
ExpectedContent: []string{"await (async function(){ext1_main})();await (async function(){ext3_main})();"},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
},
|
||||
}
|
||||
|
||||
+14
-4
@@ -10,10 +10,10 @@ import (
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/filesystem"
|
||||
"github.com/pocketbase/pocketbase/tools/list"
|
||||
"github.com/pocketbase/pocketbase/tools/router"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/filesystem"
|
||||
"github.com/tabshift-gh/pocketbase/tools/list"
|
||||
"github.com/tabshift-gh/pocketbase/tools/router"
|
||||
"github.com/spf13/cast"
|
||||
"golang.org/x/sync/semaphore"
|
||||
"golang.org/x/sync/singleflight"
|
||||
@@ -60,6 +60,7 @@ type fileApi struct {
|
||||
}
|
||||
|
||||
func (api *fileApi) fileToken(e *core.RequestEvent) error {
|
||||
// extra check for just in case the handler is called in a different context
|
||||
if e.Auth == nil {
|
||||
return e.UnauthorizedError("Missing auth context.", nil)
|
||||
}
|
||||
@@ -114,6 +115,15 @@ func (api *fileApi) download(e *core.RequestEvent) error {
|
||||
token := e.Request.URL.Query().Get("token")
|
||||
authRecord, _ := e.App.FindAuthRecordByToken(token, core.TokenTypeFile)
|
||||
|
||||
// reset the auth state if it is superuser and it is not whitelisted
|
||||
// (not critical because file tokens are short-lived but checked nonetheless as an extra precaution)
|
||||
if authRecord != nil && authRecord.IsSuperuser() {
|
||||
allowedIPs := e.App.Settings().SuperuserIPs
|
||||
if len(allowedIPs) > 0 && !isIPInList(allowedIPs, e.RealIP()) {
|
||||
authRecord = nil
|
||||
}
|
||||
}
|
||||
|
||||
// create a shallow copy of the cached request data and adjust it to the current auth record (if any)
|
||||
requestInfo := *originalRequestInfo
|
||||
requestInfo.Context = core.RequestInfoContextProtectedFile
|
||||
|
||||
+48
-4
@@ -10,10 +10,10 @@ import (
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/apis"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
"github.com/tabshift-gh/pocketbase/apis"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/tools/types"
|
||||
)
|
||||
|
||||
func TestFileToken(t *testing.T) {
|
||||
@@ -353,6 +353,50 @@ func TestFileDownload(t *testing.T) {
|
||||
"OnFileDownloadRequest": 1,
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "protected file - superuser with non-whitelisted IP",
|
||||
Method: http.MethodGet,
|
||||
URL: "/api/files/demo1/al1h9ijdeojtsjy/300_Jsjq7RdBgA.png?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsImV4cCI6MjUyNDYwNDQ2MSwidHlwZSI6ImZpbGUiLCJjb2xsZWN0aW9uSWQiOiJwYmNfMzE0MjYzNTgyMyJ9.Lupz541xRvrktwkrl55p5pPCF77T69ZRsohsIcb2dxc",
|
||||
Headers: map[string]string{"x-test-ip": "127.0.0.1"},
|
||||
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
|
||||
app.Settings().TrustedProxy = core.TrustedProxyConfig{
|
||||
Headers: []string{"x-test-ip"},
|
||||
}
|
||||
|
||||
app.Settings().SuperuserIPs = []string{"0.0.0.0"}
|
||||
|
||||
err := app.Save(app.Settings())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
},
|
||||
ExpectedStatus: 404,
|
||||
ExpectedContent: []string{`"data":{}`},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
},
|
||||
{
|
||||
Name: "protected file - superuser with whitelisted IP",
|
||||
Method: http.MethodGet,
|
||||
URL: "/api/files/demo1/al1h9ijdeojtsjy/300_Jsjq7RdBgA.png?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsImV4cCI6MjUyNDYwNDQ2MSwidHlwZSI6ImZpbGUiLCJjb2xsZWN0aW9uSWQiOiJwYmNfMzE0MjYzNTgyMyJ9.Lupz541xRvrktwkrl55p5pPCF77T69ZRsohsIcb2dxc",
|
||||
Headers: map[string]string{"x-test-ip": "127.0.0.1"},
|
||||
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
|
||||
app.Settings().TrustedProxy = core.TrustedProxyConfig{
|
||||
Headers: []string{"x-test-ip"},
|
||||
}
|
||||
|
||||
app.Settings().SuperuserIPs = []string{"127.0.0.1"}
|
||||
|
||||
if err := app.Save(app.Settings()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
},
|
||||
ExpectedStatus: 200,
|
||||
ExpectedContent: []string{"PNG"},
|
||||
ExpectedEvents: map[string]int{
|
||||
"*": 0,
|
||||
"OnFileDownloadRequest": 1,
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "protected file - guest without view access",
|
||||
Method: http.MethodGet,
|
||||
|
||||
+2
-2
@@ -4,8 +4,8 @@ import (
|
||||
"net/http"
|
||||
"slices"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/router"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/router"
|
||||
)
|
||||
|
||||
// bindHealthApi registers the health api endpoint.
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
)
|
||||
|
||||
func TestHealthAPI(t *testing.T) {
|
||||
|
||||
+4
-4
@@ -10,9 +10,9 @@ import (
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/osutils"
|
||||
"github.com/pocketbase/pocketbase/ui"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/osutils"
|
||||
"github.com/tabshift-gh/pocketbase/ui"
|
||||
)
|
||||
|
||||
// DefaultInstallerFunc is the default PocketBase installer function.
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
// token for the systemSuperuser) to the installer UI so that users can
|
||||
// create their own custom superuser record.
|
||||
//
|
||||
// See https://github.com/pocketbase/pocketbase/discussions/5814.
|
||||
// See https://github.com/tabshift-gh/pocketbase/discussions/5814.
|
||||
func DefaultInstallerFunc(app core.App, systemSuperuser *core.Record, baseURL string) error {
|
||||
if ui.DistDirFS == nil {
|
||||
color.Magenta("You can create your first superuser by running: %s superuser upsert EMAIL PASS", executablePath())
|
||||
|
||||
+3
-3
@@ -4,9 +4,9 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/router"
|
||||
"github.com/pocketbase/pocketbase/tools/search"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/router"
|
||||
"github.com/tabshift-gh/pocketbase/tools/search"
|
||||
)
|
||||
|
||||
// bindLogsApi registers the request logs api endpoints.
|
||||
|
||||
+2
-2
@@ -4,8 +4,8 @@ import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
)
|
||||
|
||||
func TestLogsList(t *testing.T) {
|
||||
|
||||
+30
-5
@@ -11,11 +11,11 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/hook"
|
||||
"github.com/pocketbase/pocketbase/tools/list"
|
||||
"github.com/pocketbase/pocketbase/tools/router"
|
||||
"github.com/pocketbase/pocketbase/tools/routine"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/hook"
|
||||
"github.com/tabshift-gh/pocketbase/tools/list"
|
||||
"github.com/tabshift-gh/pocketbase/tools/router"
|
||||
"github.com/tabshift-gh/pocketbase/tools/routine"
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
|
||||
@@ -42,6 +42,9 @@ const (
|
||||
DefaultLoadAuthTokenMiddlewarePriority = DefaultRateLimitMiddlewarePriority - 20
|
||||
DefaultLoadAuthTokenMiddlewareId = "pbLoadAuthToken"
|
||||
|
||||
DefaultSuperuserIPsWhitelistMiddlewarePriority = DefaultLoadAuthTokenMiddlewarePriority + 5
|
||||
DefaultSuperuserIPsWhitelistMiddlewareId = "pbSuperuserIPsWhitelist"
|
||||
|
||||
DefaultSecurityHeadersMiddlewarePriority = DefaultRateLimitMiddlewarePriority - 10
|
||||
DefaultSecurityHeadersMiddlewareId = "pbSecurityHeaders"
|
||||
|
||||
@@ -299,6 +302,28 @@ func securityHeaders() *hook.Handler[*core.RequestEvent] {
|
||||
}
|
||||
}
|
||||
|
||||
// superuserIPsWhitelist middleware checks the current authenticated superuser IP
|
||||
// against the configured SuperuserIPs whitelist setting.
|
||||
//
|
||||
// This middleware is registered by default for all routes.
|
||||
func superuserIPsWhitelist() *hook.Handler[*core.RequestEvent] {
|
||||
return &hook.Handler[*core.RequestEvent]{
|
||||
Id: DefaultSuperuserIPsWhitelistMiddlewareId,
|
||||
Priority: DefaultSuperuserIPsWhitelistMiddlewarePriority,
|
||||
Func: func(e *core.RequestEvent) error {
|
||||
if e.HasSuperuserAuth() {
|
||||
ips := e.App.Settings().SuperuserIPs
|
||||
|
||||
if len(ips) > 0 && !isIPInList(ips, e.RealIP()) {
|
||||
return e.ForbiddenError("", errors.New("superuser IP is not whitelisted"))
|
||||
}
|
||||
}
|
||||
|
||||
return e.Next()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// SkipSuccessActivityLog is a helper middleware that instructs the global
|
||||
// activity logger to log only requests that have failed/returned an error.
|
||||
func SkipSuccessActivityLog() *hook.Handler[*core.RequestEvent] {
|
||||
|
||||
@@ -4,9 +4,9 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/hook"
|
||||
"github.com/pocketbase/pocketbase/tools/router"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/hook"
|
||||
"github.com/tabshift-gh/pocketbase/tools/router"
|
||||
)
|
||||
|
||||
var ErrRequestEntityTooLarge = router.NewApiError(http.StatusRequestEntityTooLarge, "Request entity too large", nil)
|
||||
|
||||
@@ -6,9 +6,9 @@ import (
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/apis"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/apis"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
)
|
||||
|
||||
func TestBodyLimitMiddleware(t *testing.T) {
|
||||
|
||||
@@ -19,8 +19,8 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/hook"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/hook"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -17,9 +17,9 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/hook"
|
||||
"github.com/pocketbase/pocketbase/tools/router"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/hook"
|
||||
"github.com/tabshift-gh/pocketbase/tools/router"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -2,12 +2,13 @@ package apis
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/netip"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/hook"
|
||||
"github.com/pocketbase/pocketbase/tools/store"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/hook"
|
||||
"github.com/tabshift-gh/pocketbase/tools/store"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -106,6 +107,41 @@ func checkCollectionRateLimit(e *core.RequestEvent, collection *core.Collection,
|
||||
return nil
|
||||
}
|
||||
|
||||
// isIPInList checks if the specified IP is in a list of other individual IPs or subnets.
|
||||
func isIPInList(ipsOrSubnets []string, ip string) bool {
|
||||
if len(ipsOrSubnets) == 0 || ip == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
// normalize
|
||||
searchAddr, err := netip.ParseAddr(ip)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, item := range ipsOrSubnets {
|
||||
// subnet?
|
||||
prefix, err := netip.ParsePrefix(item)
|
||||
if err == nil {
|
||||
if prefix.Contains(searchAddr) {
|
||||
return true
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// individual ip?
|
||||
addr, err := netip.ParseAddr(item)
|
||||
if err == nil {
|
||||
if addr == searchAddr {
|
||||
return true
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
|
||||
// @todo consider exporting as helper?
|
||||
@@ -153,7 +189,9 @@ func checkRateLimit(e *core.RequestEvent, rtId string, rule core.RateLimitRule)
|
||||
}
|
||||
|
||||
func skipRateLimit(e *core.RequestEvent) bool {
|
||||
return !e.App.Settings().RateLimits.Enabled || e.HasSuperuserAuth()
|
||||
return !e.App.Settings().RateLimits.Enabled ||
|
||||
e.HasSuperuserAuth() ||
|
||||
isIPInList(e.App.Settings().RateLimits.ExcludedIPs, e.RealIP())
|
||||
}
|
||||
|
||||
var defaultAuthAudience = []string{core.RateLimitRuleAudienceAll, core.RateLimitRuleAudienceAuth}
|
||||
|
||||
@@ -5,9 +5,10 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/apis"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/apis"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/tools/hook"
|
||||
)
|
||||
|
||||
func TestDefaultRateLimitMiddleware(t *testing.T) {
|
||||
@@ -85,9 +86,8 @@ func TestDefaultRateLimitMiddleware(t *testing.T) {
|
||||
{"/norate", 0, false, 200},
|
||||
|
||||
{"/rate/a", 0, false, 200},
|
||||
{"/rate/a", 800, false, 200}, // (fixed window check) wait enough to ensure that it can't fit more than 2 requests in 1s
|
||||
{"/rate/a", 600, false, 200},
|
||||
{"/rate/a", 850, false, 200},
|
||||
{"/rate/a", 900, false, 200}, // (fixed window check) wait enough to ensure that it can't fit more than 2 requests in 1s
|
||||
{"/rate/a", 900, false, 200},
|
||||
{"/rate/a", 0, false, 200},
|
||||
{"/rate/a", 0, false, 429},
|
||||
{"/rate/a", 0, false, 429},
|
||||
@@ -160,3 +160,163 @@ func TestDefaultRateLimitMiddleware(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultRateLimitMiddlewareSkipChecks(t *testing.T) {
|
||||
app, _ := tests.NewTestApp()
|
||||
defer app.Cleanup()
|
||||
|
||||
app.Settings().RateLimits.Enabled = true
|
||||
app.Settings().RateLimits.Rules = []core.RateLimitRule{
|
||||
{
|
||||
Label: "/rate",
|
||||
MaxRequests: 1,
|
||||
Duration: 5,
|
||||
},
|
||||
}
|
||||
|
||||
pbRouter, err := apis.NewRouter(app)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// just for the exclude tests - load the user IP from a query param
|
||||
pbRouter.Bind(&hook.Handler[*core.RequestEvent]{
|
||||
Priority: apis.DefaultRateLimitMiddlewarePriority - 1,
|
||||
Func: func(e *core.RequestEvent) error {
|
||||
testIp := e.Request.URL.Query().Get("testIP")
|
||||
if testIp != "" {
|
||||
e.Request.Header.Set("x-test-ip", testIp)
|
||||
}
|
||||
|
||||
return e.Next()
|
||||
},
|
||||
})
|
||||
|
||||
pbRouter.GET("/rate", func(e *core.RequestEvent) error {
|
||||
return e.String(200, "test")
|
||||
})
|
||||
|
||||
mux, err := pbRouter.BuildMux()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
checkStatusCodes := func(t *testing.T, got []int, expected []int) {
|
||||
if len(expected) != len(got) {
|
||||
t.Fatalf("Expected status codes %v, got %v", expected, got)
|
||||
}
|
||||
|
||||
for i, item := range expected {
|
||||
if got[i] != item {
|
||||
t.Fatalf("Expected %d status code to be %d, got %d:\n%v", i, item, got[i], got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("base check", func(t *testing.T) {
|
||||
app.Settings().RateLimits.Enabled = true
|
||||
|
||||
statusCodes := []int{}
|
||||
for range 3 {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("GET", "/rate", nil)
|
||||
|
||||
mux.ServeHTTP(rec, req)
|
||||
|
||||
result := rec.Result()
|
||||
|
||||
statusCodes = append(statusCodes, result.StatusCode)
|
||||
}
|
||||
|
||||
checkStatusCodes(t, statusCodes, []int{200, 429, 429})
|
||||
})
|
||||
|
||||
t.Run("disabled rate limiter", func(t *testing.T) {
|
||||
app.Settings().RateLimits.Enabled = false
|
||||
|
||||
statusCodes := []int{}
|
||||
for range 3 {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("GET", "/rate", nil)
|
||||
|
||||
mux.ServeHTTP(rec, req)
|
||||
|
||||
result := rec.Result()
|
||||
|
||||
statusCodes = append(statusCodes, result.StatusCode)
|
||||
}
|
||||
|
||||
checkStatusCodes(t, statusCodes, []int{200, 200, 200})
|
||||
})
|
||||
|
||||
t.Run("authenticated as superuser", func(t *testing.T) {
|
||||
app.Settings().RateLimits.Enabled = true
|
||||
|
||||
superuser, err := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test@example.com")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
token, err := superuser.NewAuthToken()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
statusCodes := []int{}
|
||||
for range 3 {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("GET", "/rate", nil)
|
||||
req.Header.Add("Authorization", token)
|
||||
|
||||
mux.ServeHTTP(rec, req)
|
||||
|
||||
result := rec.Result()
|
||||
|
||||
statusCodes = append(statusCodes, result.StatusCode)
|
||||
}
|
||||
|
||||
checkStatusCodes(t, statusCodes, []int{200, 200, 200})
|
||||
})
|
||||
|
||||
t.Run("excludedIPs (different)", func(t *testing.T) {
|
||||
app.Settings().RateLimits.Enabled = true
|
||||
app.Settings().RateLimits.ExcludedIPs = []string{"10.0.0.0"}
|
||||
app.Settings().TrustedProxy.Headers = []string{"x-test-ip"}
|
||||
|
||||
statusCodes := []int{}
|
||||
for range 3 {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("GET", "/rate", nil)
|
||||
req.Header.Set("x-test-ip", "127.0.0.1")
|
||||
|
||||
mux.ServeHTTP(rec, req)
|
||||
|
||||
result := rec.Result()
|
||||
|
||||
statusCodes = append(statusCodes, result.StatusCode)
|
||||
}
|
||||
|
||||
checkStatusCodes(t, statusCodes, []int{200, 429, 429})
|
||||
})
|
||||
|
||||
t.Run("excludedIPs (match)", func(t *testing.T) {
|
||||
app.Settings().RateLimits.Enabled = true
|
||||
app.Settings().RateLimits.ExcludedIPs = []string{"127.0.0.1"}
|
||||
app.Settings().TrustedProxy.Headers = []string{"x-test-ip"}
|
||||
|
||||
statusCodes := []int{}
|
||||
for range 3 {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("GET", "/rate", nil)
|
||||
req.Header.Set("x-test-ip", "127.0.0.1")
|
||||
|
||||
mux.ServeHTTP(rec, req)
|
||||
|
||||
result := rec.Result()
|
||||
|
||||
statusCodes = append(statusCodes, result.StatusCode)
|
||||
}
|
||||
|
||||
checkStatusCodes(t, statusCodes, []int{200, 200, 200})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -4,9 +4,9 @@ import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/apis"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/apis"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
)
|
||||
|
||||
func TestPanicRecover(t *testing.T) {
|
||||
@@ -553,3 +553,96 @@ func TestRequireSameCollectionContextAuth(t *testing.T) {
|
||||
scenario.Test(t)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuperuserIPsWhitelist(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
setupWhitelist := func(superuserIPs ...string) func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
|
||||
return func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
|
||||
// allow loading a mock IP from the test scenario
|
||||
app.Settings().TrustedProxy = core.TrustedProxyConfig{
|
||||
Headers: []string{"x-test-ip"},
|
||||
}
|
||||
|
||||
app.Settings().SuperuserIPs = superuserIPs
|
||||
|
||||
err := app.Save(app.Settings())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
e.Router.GET("/my/test", func(e *core.RequestEvent) error {
|
||||
return e.String(200, "test123")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
scenarios := []tests.ApiScenario{
|
||||
{
|
||||
Name: "guest with non-matching IP",
|
||||
Method: http.MethodGet,
|
||||
URL: "/my/test",
|
||||
Headers: map[string]string{"x-test-ip": "127.0.0.1"},
|
||||
BeforeTestFunc: setupWhitelist("0.0.0.0"),
|
||||
ExpectedStatus: 200,
|
||||
ExpectedContent: []string{"test123"},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
},
|
||||
{
|
||||
Name: "regular user with non-matching IP",
|
||||
Method: http.MethodGet,
|
||||
URL: "/my/test",
|
||||
Headers: map[string]string{
|
||||
"x-test-ip": "127.0.0.1",
|
||||
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
|
||||
},
|
||||
BeforeTestFunc: setupWhitelist("0.0.0.0"),
|
||||
ExpectedStatus: 200,
|
||||
ExpectedContent: []string{"test123"},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
},
|
||||
{
|
||||
Name: "superuser with non-matching IP",
|
||||
Method: http.MethodGet,
|
||||
URL: "/my/test",
|
||||
Headers: map[string]string{
|
||||
"x-test-ip": "127.0.0.1",
|
||||
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
|
||||
},
|
||||
BeforeTestFunc: setupWhitelist("0.0.0.0"),
|
||||
ExpectedStatus: 403,
|
||||
ExpectedContent: []string{`"data":{}`},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
},
|
||||
{
|
||||
Name: "superuser with matching IP",
|
||||
Method: http.MethodGet,
|
||||
URL: "/my/test",
|
||||
Headers: map[string]string{
|
||||
"x-test-ip": "127.0.0.1",
|
||||
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
|
||||
},
|
||||
BeforeTestFunc: setupWhitelist("0.0.0.0", "127.0.0.1"),
|
||||
ExpectedStatus: 200,
|
||||
ExpectedContent: []string{"test123"},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
},
|
||||
{
|
||||
Name: "superuser with no whitelisted IPs",
|
||||
Method: http.MethodGet,
|
||||
URL: "/my/test",
|
||||
Headers: map[string]string{
|
||||
"x-test-ip": "127.0.0.1",
|
||||
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
|
||||
},
|
||||
BeforeTestFunc: setupWhitelist(),
|
||||
ExpectedStatus: 200,
|
||||
ExpectedContent: []string{"test123"},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
},
|
||||
}
|
||||
|
||||
for _, scenario := range scenarios {
|
||||
scenario.Test(t)
|
||||
}
|
||||
}
|
||||
|
||||
+151
-30
@@ -10,15 +10,15 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
validation "github.com/go-ozzo/ozzo-validation/v4"
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/hook"
|
||||
"github.com/pocketbase/pocketbase/tools/picker"
|
||||
"github.com/pocketbase/pocketbase/tools/router"
|
||||
"github.com/pocketbase/pocketbase/tools/routine"
|
||||
"github.com/pocketbase/pocketbase/tools/search"
|
||||
"github.com/pocketbase/pocketbase/tools/subscriptions"
|
||||
validation "github.com/pocketbase/ozzo-validation/v4"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/hook"
|
||||
"github.com/tabshift-gh/pocketbase/tools/picker"
|
||||
"github.com/tabshift-gh/pocketbase/tools/router"
|
||||
"github.com/tabshift-gh/pocketbase/tools/routine"
|
||||
"github.com/tabshift-gh/pocketbase/tools/search"
|
||||
"github.com/tabshift-gh/pocketbase/tools/subscriptions"
|
||||
"golang.org/x/sync/errgroup"
|
||||
)
|
||||
|
||||
@@ -28,6 +28,9 @@ const clientsChunkSize = 150
|
||||
// RealtimeClientAuthKey is the name of the realtime client store key that holds its auth state.
|
||||
const RealtimeClientAuthKey = "auth"
|
||||
|
||||
// RealtimeClientIPKey is the name of the realtime client store key that holds the IP of the connected client.
|
||||
const RealtimeClientIPKey = "pbRealtimeClientIP"
|
||||
|
||||
// bindRealtimeApi registers the realtime api endpoints.
|
||||
func bindRealtimeApi(app core.App, rg *router.RouterGroup[*core.RequestEvent]) {
|
||||
sub := rg.Group("/realtime")
|
||||
@@ -57,14 +60,18 @@ func realtimeConnect(e *core.RequestEvent) error {
|
||||
|
||||
e.Response.Header().Set("Content-Type", "text/event-stream")
|
||||
e.Response.Header().Set("Cache-Control", "no-store")
|
||||
// https://github.com/pocketbase/pocketbase/discussions/480#discussioncomment-3657640
|
||||
// https://github.com/tabshift-gh/pocketbase/discussions/480#discussioncomment-3657640
|
||||
// https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffering
|
||||
e.Response.Header().Set("X-Accel-Buffering", "no")
|
||||
|
||||
connectEvent := new(core.RealtimeConnectRequestEvent)
|
||||
connectEvent.RequestEvent = e
|
||||
connectEvent.Client = subscriptions.NewDefaultClient()
|
||||
connectEvent.IdleTimeout = 5 * time.Minute
|
||||
connectEvent.MaxTimeout = 30 * time.Minute
|
||||
connectEvent.Client = subscriptions.NewDefaultClient()
|
||||
|
||||
// could be used as an optional cross-reference check in other API endpoints
|
||||
connectEvent.Client.Set(RealtimeClientIPKey, e.RealIP())
|
||||
|
||||
return e.App.OnRealtimeConnectRequest().Trigger(connectEvent, func(ce *core.RealtimeConnectRequestEvent) error {
|
||||
// register new subscription client
|
||||
@@ -73,7 +80,7 @@ func realtimeConnect(e *core.RequestEvent) error {
|
||||
e.App.SubscriptionsBroker().Unregister(ce.Client.Id())
|
||||
}()
|
||||
|
||||
ce.App.Logger().Debug("Realtime connection established.", slog.String("clientId", ce.Client.Id()))
|
||||
ce.App.Logger().Debug("Realtime connection established", slog.String("clientId", ce.Client.Id()))
|
||||
|
||||
// signalize established connection (aka. fire "connect" message)
|
||||
connectMsgEvent := new(core.RealtimeMessageEvent)
|
||||
@@ -99,12 +106,19 @@ func realtimeConnect(e *core.RequestEvent) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// start a max lifetime timer to prevent accumulating too much
|
||||
// connection resources and to allow the GC to run more regularly
|
||||
maxTimer := time.NewTimer(ce.MaxTimeout)
|
||||
defer maxTimer.Stop()
|
||||
|
||||
// start an idle timer to keep track of inactive/forgotten connections
|
||||
idleTimer := time.NewTimer(ce.IdleTimeout)
|
||||
defer idleTimer.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-maxTimer.C:
|
||||
cancelRequest()
|
||||
case <-idleTimer.C:
|
||||
cancelRequest()
|
||||
case msg, ok := <-ce.Client.Channel():
|
||||
@@ -186,6 +200,21 @@ func realtimeSetSubscriptions(e *core.RequestEvent) error {
|
||||
return e.NotFoundError("Missing or invalid client id.", err)
|
||||
}
|
||||
|
||||
// for just in case to prevent someone changing a guest subscription
|
||||
//
|
||||
// note1: this is an extra precaution against clientId bruteforce attempts
|
||||
// for installations allowing longer realtime connections duration
|
||||
//
|
||||
// note2: custom registered clients (aka. those without IP in the store)
|
||||
// are excluded from the check for backward compatibility
|
||||
clientIP, _ := client.Get(RealtimeClientIPKey).(string)
|
||||
if clientIP != "" && clientIP != e.RealIP() {
|
||||
return e.BadRequestError(
|
||||
"Invalid realtime client.",
|
||||
errors.New("the subscription request IP doesn't match with the realtime client IP"),
|
||||
)
|
||||
}
|
||||
|
||||
// for now allow only guest->auth upgrades and any other auth change is forbidden
|
||||
clientAuth, _ := client.Get(RealtimeClientAuthKey).(*core.Record)
|
||||
if clientAuth != nil && !isSameAuth(clientAuth, e.Auth) {
|
||||
@@ -208,7 +237,7 @@ func realtimeSetSubscriptions(e *core.RequestEvent) error {
|
||||
e.Client.Subscribe(e.Subscriptions...)
|
||||
|
||||
e.App.Logger().Debug(
|
||||
"Realtime subscriptions updated.",
|
||||
"Realtime subscriptions updated",
|
||||
slog.String("clientId", e.Client.Id()),
|
||||
slog.Any("subscriptions", e.Subscriptions),
|
||||
)
|
||||
@@ -219,38 +248,47 @@ func realtimeSetSubscriptions(e *core.RequestEvent) error {
|
||||
})
|
||||
}
|
||||
|
||||
// updateClientsAuth updates the existing clients auth record with the new one (matched by ID).
|
||||
func realtimeUpdateClientsAuth(app core.App, newAuthRecord *core.Record) error {
|
||||
// realtimeUpdateClientsAuth updates the auth state of all clients related to the provided authRecord.
|
||||
//
|
||||
// Realtime connections has short lifetime by design, but to minimize abuse
|
||||
// if the new record has a different tokenKey (e.g. in case of password reset)
|
||||
// the auth state of the related realtime connections is also cleared
|
||||
// (aka. they remain active but unauthenticated, allowing to reauthenicate with the next subscription).
|
||||
func realtimeUpdateClientsAuth(app core.App, authRecord *core.Record) error {
|
||||
chunks := app.SubscriptionsBroker().ChunkedClients(clientsChunkSize)
|
||||
|
||||
group := new(errgroup.Group)
|
||||
|
||||
for _, chunk := range chunks {
|
||||
group.Go(func() error {
|
||||
group.Go(routine.SafeWrap(func() error {
|
||||
for _, client := range chunk {
|
||||
clientAuth, _ := client.Get(RealtimeClientAuthKey).(*core.Record)
|
||||
if clientAuth != nil &&
|
||||
clientAuth.Id == newAuthRecord.Id &&
|
||||
clientAuth.Collection().Name == newAuthRecord.Collection().Name {
|
||||
client.Set(RealtimeClientAuthKey, newAuthRecord)
|
||||
clientAuth.Id == authRecord.Id &&
|
||||
clientAuth.Collection().Name == authRecord.Collection().Name {
|
||||
if clientAuth.TokenKey() != authRecord.TokenKey() {
|
||||
client.Unset(RealtimeClientAuthKey)
|
||||
} else {
|
||||
client.Set(RealtimeClientAuthKey, authRecord)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
return group.Wait()
|
||||
}
|
||||
|
||||
// realtimeUnsetClientsAuthState unsets the auth state of all clients that have the provided auth model.
|
||||
func realtimeUnsetClientsAuthState(app core.App, authModel core.Model) error {
|
||||
// realtimeUnsetClientsAuthByRecordModelOrProxy unsets the auth state of all clients that have the provided auth model.
|
||||
func realtimeUnsetClientsAuthByRecordModelOrProxy(app core.App, authModel core.Model) error {
|
||||
chunks := app.SubscriptionsBroker().ChunkedClients(clientsChunkSize)
|
||||
|
||||
group := new(errgroup.Group)
|
||||
|
||||
for _, chunk := range chunks {
|
||||
group.Go(func() error {
|
||||
group.Go(routine.SafeWrap(func() error {
|
||||
for _, client := range chunk {
|
||||
clientAuth, _ := client.Get(RealtimeClientAuthKey).(*core.Record)
|
||||
if clientAuth != nil &&
|
||||
@@ -261,13 +299,82 @@ func realtimeUnsetClientsAuthState(app core.App, authModel core.Model) error {
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
return group.Wait()
|
||||
}
|
||||
|
||||
// realtimeUnsetClientsAuthByCollection unsets the auth state of all authenticated clients related to the collection.
|
||||
func realtimeUnsetClientsAuthByCollection(app core.App, collection *core.Collection) error {
|
||||
chunks := app.SubscriptionsBroker().ChunkedClients(clientsChunkSize)
|
||||
|
||||
group := new(errgroup.Group)
|
||||
|
||||
for _, chunk := range chunks {
|
||||
group.Go(routine.SafeWrap(func() error {
|
||||
for _, client := range chunk {
|
||||
clientAuth, _ := client.Get(RealtimeClientAuthKey).(*core.Record)
|
||||
if clientAuth != nil && clientAuth.Collection().Name == collection.Name {
|
||||
client.Unset(RealtimeClientAuthKey)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}))
|
||||
}
|
||||
|
||||
return group.Wait()
|
||||
}
|
||||
|
||||
func bindRealtimeEvents(app core.App) {
|
||||
// reset the clients auth on collection secret change
|
||||
// (@todo with the future tracking of old collections data consider replacing with *AfterUpdateSuccess to account for transaction rollback)
|
||||
app.OnCollectionUpdate().Bind(&hook.Handler[*core.CollectionEvent]{
|
||||
Func: func(e *core.CollectionEvent) error {
|
||||
if !e.Collection.IsAuth() {
|
||||
return e.Next()
|
||||
}
|
||||
|
||||
cached, _ := e.App.FindCachedCollectionByNameOrId(e.Collection.Id)
|
||||
|
||||
if err := e.Next(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if cached != nil && cached.AuthToken.Secret != e.Collection.AuthToken.Secret {
|
||||
if err := realtimeUnsetClientsAuthByCollection(e.App, e.Collection); err != nil {
|
||||
app.Logger().Warn(
|
||||
"Failed to remove client(s) associated to the changed auth collection",
|
||||
slog.String("collectionName", e.Collection.Name),
|
||||
slog.String("error", err.Error()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
Priority: -99,
|
||||
})
|
||||
|
||||
// unset the clients auth on auth collection delete
|
||||
app.OnCollectionAfterDeleteSuccess().Bind(&hook.Handler[*core.CollectionEvent]{
|
||||
Func: func(e *core.CollectionEvent) error {
|
||||
if e.Collection.IsAuth() {
|
||||
if err := realtimeUnsetClientsAuthByCollection(e.App, e.Collection); err != nil {
|
||||
app.Logger().Warn(
|
||||
"Failed to remove client(s) associated to the deleted auth collection",
|
||||
slog.String("collectionName", e.Collection.Name),
|
||||
slog.String("error", err.Error()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return e.Next()
|
||||
},
|
||||
Priority: -99,
|
||||
})
|
||||
|
||||
// update the clients that has auth record association
|
||||
app.OnModelAfterUpdateSuccess().Bind(&hook.Handler[*core.ModelEvent]{
|
||||
Func: func(e *core.ModelEvent) error {
|
||||
@@ -294,7 +401,7 @@ func bindRealtimeEvents(app core.App) {
|
||||
Func: func(e *core.ModelEvent) error {
|
||||
collection := realtimeResolveRecordCollection(e.App, e.Model)
|
||||
if collection != nil && collection.IsAuth() {
|
||||
if err := realtimeUnsetClientsAuthState(e.App, e.Model); err != nil {
|
||||
if err := realtimeUnsetClientsAuthByRecordModelOrProxy(e.App, e.Model); err != nil {
|
||||
app.Logger().Warn(
|
||||
"Failed to remove client(s) associated to the deleted auth model",
|
||||
slog.Any("id", e.Model.PK()),
|
||||
@@ -516,7 +623,7 @@ func realtimeBroadcastRecord(app core.App, action string, record *core.Record, d
|
||||
}
|
||||
|
||||
for _, chunk := range chunks {
|
||||
group.Go(func() error {
|
||||
group.Go(routine.SafeWrap(func() error {
|
||||
var clientAuth *core.Record
|
||||
|
||||
for _, client := range chunk {
|
||||
@@ -548,6 +655,20 @@ func realtimeBroadcastRecord(app core.App, action string, record *core.Record, d
|
||||
// which exact fields the client subscription requested or has permissions to access
|
||||
cleanRecord := record.Fresh()
|
||||
|
||||
// -------------------------------------------
|
||||
// @todo consider with the refactoring whether
|
||||
// the default enriching used by the regular APIs
|
||||
// can be reused here too to avoid eventual future
|
||||
// discrepencies in the record event data
|
||||
//
|
||||
// https://github.com/pocketbase/pocketbase/issues/7721
|
||||
// -------------------------------------------
|
||||
|
||||
// enable hidden fields for superuser subscribers
|
||||
if requestInfo.HasSuperuserAuth() {
|
||||
cleanRecord.Unhide(collection.Fields.FieldNames()...)
|
||||
}
|
||||
|
||||
// trigger the enrich hooks
|
||||
enrichErr := triggerRecordEnrichHooks(app, requestInfo, []*core.Record{cleanRecord}, func() error {
|
||||
// apply expand
|
||||
@@ -645,7 +766,7 @@ func realtimeBroadcastRecord(app core.App, action string, record *core.Record, d
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
return group.Wait()
|
||||
@@ -661,7 +782,7 @@ func realtimeBroadcastDryCacheKey(app core.App, key string) error {
|
||||
group := new(errgroup.Group)
|
||||
|
||||
for _, chunk := range chunks {
|
||||
group.Go(func() error {
|
||||
group.Go(routine.SafeWrap(func() error {
|
||||
for _, client := range chunk {
|
||||
messages, ok := client.Get(key).([]subscriptions.Message)
|
||||
if !ok {
|
||||
@@ -680,7 +801,7 @@ func realtimeBroadcastDryCacheKey(app core.App, key string) error {
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
return group.Wait()
|
||||
@@ -696,7 +817,7 @@ func realtimeUnsetDryCacheKey(app core.App, key string) error {
|
||||
group := new(errgroup.Group)
|
||||
|
||||
for _, chunk := range chunks {
|
||||
group.Go(func() error {
|
||||
group.Go(routine.SafeWrap(func() error {
|
||||
for _, client := range chunk {
|
||||
if client.Get(key) != nil {
|
||||
client.Unset(key)
|
||||
@@ -704,7 +825,7 @@ func realtimeUnsetDryCacheKey(app core.App, key string) error {
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
return group.Wait()
|
||||
|
||||
+376
-22
@@ -13,11 +13,11 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/apis"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/pocketbase/pocketbase/tools/subscriptions"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
"github.com/tabshift-gh/pocketbase/apis"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/tools/subscriptions"
|
||||
"github.com/tabshift-gh/pocketbase/tools/types"
|
||||
)
|
||||
|
||||
func TestRealtimeConnect(t *testing.T) {
|
||||
@@ -26,6 +26,7 @@ func TestRealtimeConnect(t *testing.T) {
|
||||
Method: http.MethodGet,
|
||||
URL: "/api/realtime",
|
||||
Timeout: 100 * time.Millisecond,
|
||||
Headers: map[string]string{"x-test-ip": "127.0.0.2"},
|
||||
ExpectedStatus: 200,
|
||||
ExpectedContent: []string{
|
||||
`id:`,
|
||||
@@ -37,6 +38,17 @@ func TestRealtimeConnect(t *testing.T) {
|
||||
"OnRealtimeConnectRequest": 1,
|
||||
"OnRealtimeMessageSend": 1,
|
||||
},
|
||||
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
|
||||
app.Settings().TrustedProxy.Headers = []string{"x-test-ip"}
|
||||
|
||||
app.OnRealtimeConnectRequest().BindFunc(func(e *core.RealtimeConnectRequestEvent) error {
|
||||
if ip, _ := e.Client.Get(apis.RealtimeClientIPKey).(string); ip != "127.0.0.2" {
|
||||
t.Fatalf("Expected IP %q, got %q", "127.0.0.2", ip)
|
||||
}
|
||||
|
||||
return e.Next()
|
||||
})
|
||||
},
|
||||
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
|
||||
if len(app.SubscriptionsBroker().Clients()) != 0 {
|
||||
t.Errorf("Expected the subscribers to be removed after connection close, found %d", len(app.SubscriptionsBroker().Clients()))
|
||||
@@ -102,7 +114,8 @@ func TestRealtimeSubscribe(t *testing.T) {
|
||||
|
||||
resetClient := func() {
|
||||
client.Unsubscribe()
|
||||
client.Set(apis.RealtimeClientAuthKey, nil)
|
||||
client.Unset(apis.RealtimeClientAuthKey)
|
||||
client.Unset(apis.RealtimeClientIPKey)
|
||||
}
|
||||
|
||||
validSubscriptionsLimit := make([]string, 1000)
|
||||
@@ -208,6 +221,26 @@ func TestRealtimeSubscribe(t *testing.T) {
|
||||
},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
},
|
||||
{
|
||||
Name: "existing client with different IP",
|
||||
Method: http.MethodPost,
|
||||
URL: "/api/realtime",
|
||||
Body: strings.NewReader(`{"clientId":"` + client.Id() + `","subscriptions":["test"]}`),
|
||||
Headers: map[string]string{"x-test-ip": "127.0.0.2"},
|
||||
ExpectedStatus: 400,
|
||||
ExpectedContent: []string{`"data":{}`},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
|
||||
app.Settings().TrustedProxy.Headers = []string{"x-test-ip"}
|
||||
|
||||
client.Set(apis.RealtimeClientIPKey, "127.0.0.1")
|
||||
|
||||
app.SubscriptionsBroker().Register(client)
|
||||
},
|
||||
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
|
||||
resetClient()
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "existing client with valid topic length",
|
||||
Method: http.MethodPost,
|
||||
@@ -429,7 +462,10 @@ func TestRealtimeAuthRecordDeleteEvent(t *testing.T) {
|
||||
defer testApp.Cleanup()
|
||||
|
||||
// init realtime handlers
|
||||
apis.NewRouter(testApp)
|
||||
_, err := apis.NewRouter(testApp)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
authRecord1, err := testApp.FindAuthRecordByEmail("users", "test@example.com")
|
||||
if err != nil {
|
||||
@@ -460,7 +496,10 @@ func TestRealtimeAuthRecordDeleteEvent(t *testing.T) {
|
||||
e.Context = context.Background()
|
||||
e.Model = authRecord1
|
||||
|
||||
testApp.OnModelAfterDeleteSuccess().Trigger(e)
|
||||
err = testApp.OnModelAfterDeleteSuccess().Trigger(e)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if total := len(testApp.SubscriptionsBroker().Clients()); total != 3 {
|
||||
t.Fatalf("Expected %d subscription clients, found %d", 3, total)
|
||||
@@ -484,7 +523,10 @@ func TestRealtimeAuthRecordUpdateEvent(t *testing.T) {
|
||||
defer testApp.Cleanup()
|
||||
|
||||
// init realtime handlers
|
||||
apis.NewRouter(testApp)
|
||||
_, err := apis.NewRouter(testApp)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
authRecord1, err := testApp.FindAuthRecordByEmail("users", "test@example.com")
|
||||
if err != nil {
|
||||
@@ -495,25 +537,331 @@ func TestRealtimeAuthRecordUpdateEvent(t *testing.T) {
|
||||
client.Set(apis.RealtimeClientAuthKey, authRecord1)
|
||||
testApp.SubscriptionsBroker().Register(client)
|
||||
|
||||
// refetch the authRecord and change its email
|
||||
// refetch the authRecord and change its name
|
||||
authRecord2, err := testApp.FindAuthRecordByEmail("users", "test@example.com")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
authRecord2.SetEmail("new@example.com")
|
||||
|
||||
// mock update event
|
||||
e := new(core.ModelEvent)
|
||||
e.App = testApp
|
||||
e.Type = core.ModelEventTypeUpdate
|
||||
e.Context = context.Background()
|
||||
e.Model = authRecord2
|
||||
newName := "test_new_name"
|
||||
authRecord2.Set("name", newName)
|
||||
|
||||
testApp.OnModelAfterUpdateSuccess().Trigger(e)
|
||||
err = testApp.Save(authRecord2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
clientAuthRecord, _ := client.Get(apis.RealtimeClientAuthKey).(*core.Record)
|
||||
if clientAuthRecord.Email() != authRecord2.Email() {
|
||||
t.Fatalf("Expected authRecord with email %q, got %q", authRecord2.Email(), clientAuthRecord.Email())
|
||||
if clientAuthRecord.Get("name") != newName {
|
||||
t.Fatalf("Expected authRecord with email %q, got %q", newName, clientAuthRecord.Email())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRealtimeRecordHiddenFields(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
testApp, _ := tests.NewTestApp()
|
||||
defer testApp.Cleanup()
|
||||
|
||||
// init realtime handlers
|
||||
_, err := apis.NewRouter(testApp)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// create temp collection with hidden fields
|
||||
testCollection := core.NewBaseCollection("test_realtime")
|
||||
testCollection.ListRule = types.Pointer("@request.auth.id != ''")
|
||||
testCollection.Fields.Add(
|
||||
&core.TextField{Name: "public"},
|
||||
&core.TextField{Name: "hidden", Hidden: true},
|
||||
)
|
||||
if err := testApp.Save(testCollection); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
testSubscription := testCollection.Name + "/*"
|
||||
|
||||
// register guest subscriber
|
||||
guestClient := subscriptions.NewDefaultClient()
|
||||
guestClient.Subscribe(testSubscription)
|
||||
testApp.SubscriptionsBroker().Register(guestClient)
|
||||
|
||||
// register regular user subscriber
|
||||
regular, err := testApp.FindAuthRecordByEmail("users", "test@example.com")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
regularClient := subscriptions.NewDefaultClient()
|
||||
regularClient.Set(apis.RealtimeClientAuthKey, regular)
|
||||
regularClient.Subscribe(testSubscription)
|
||||
testApp.SubscriptionsBroker().Register(regularClient)
|
||||
|
||||
// register superuser subscriber
|
||||
superuser, err := testApp.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test@example.com")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
superuserClient := subscriptions.NewDefaultClient()
|
||||
superuserClient.Set(apis.RealtimeClientAuthKey, superuser)
|
||||
superuserClient.Subscribe(testSubscription)
|
||||
testApp.SubscriptionsBroker().Register(superuserClient)
|
||||
|
||||
enrichCalls := map[string]int{}
|
||||
testApp.OnRecordEnrich(testCollection.Name).BindFunc(func(e *core.RecordEnrichEvent) error {
|
||||
var id string
|
||||
if e.RequestInfo.Auth != nil {
|
||||
id = e.RequestInfo.Auth.Id
|
||||
}
|
||||
enrichCalls[id]++
|
||||
return e.Next()
|
||||
})
|
||||
|
||||
timeout := time.After(3 * time.Second)
|
||||
done := make(chan struct{})
|
||||
|
||||
// collect first received messages
|
||||
var regularMessageData, superuserMessageData string
|
||||
go func() {
|
||||
regularMessageData = string((<-regularClient.Channel()).Data)
|
||||
superuserMessageData = string((<-superuserClient.Channel()).Data)
|
||||
done <- struct{}{}
|
||||
}()
|
||||
|
||||
// broadcast create message
|
||||
testRecord := core.NewRecord(testCollection)
|
||||
testRecord.Set("public", "test1")
|
||||
testRecord.Set("hidden", "test2")
|
||||
if err := testApp.Save(testRecord); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// wait for the events
|
||||
select {
|
||||
case <-timeout:
|
||||
t.Fatal("realtime test messages timeout")
|
||||
case <-done:
|
||||
// ready
|
||||
}
|
||||
|
||||
if total := len(enrichCalls); total != 2 {
|
||||
t.Fatalf("Expected %d enrich hook calls, got %d", 2, total)
|
||||
}
|
||||
|
||||
if total := enrichCalls[regular.Id]; total != 1 {
|
||||
t.Fatalf("Expected exactly 1 regular user enrich hook call, got %d", total)
|
||||
}
|
||||
|
||||
if total := enrichCalls[superuser.Id]; total != 1 {
|
||||
t.Fatalf("Expected exactly 1 superuser enrich hook call, got %d", total)
|
||||
}
|
||||
|
||||
// validate messages content
|
||||
scenarios := map[string]bool{
|
||||
"regular message public field should exist": strings.Contains(regularMessageData, `"public":`),
|
||||
"regular message hidden field should NOT exist": !strings.Contains(regularMessageData, `"hidden":`),
|
||||
"superuser message public field should exist": strings.Contains(superuserMessageData, `"public":`),
|
||||
"superuser message hidden field should exist": strings.Contains(superuserMessageData, `"hidden":`),
|
||||
}
|
||||
for name, valid := range scenarios {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
if !valid {
|
||||
t.Fatal("Invalid realtime message expectation")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRealtimeAuthRecordUnsetOnTokenKeyRefresh(t *testing.T) {
|
||||
testApp, _ := tests.NewTestApp()
|
||||
defer testApp.Cleanup()
|
||||
|
||||
// init realtime handlers
|
||||
_, err := apis.NewRouter(testApp)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
authRecord1, err := testApp.FindAuthRecordByEmail("users", "test@example.com")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
client := subscriptions.NewDefaultClient()
|
||||
client.Set(apis.RealtimeClientAuthKey, authRecord1)
|
||||
testApp.SubscriptionsBroker().Register(client)
|
||||
|
||||
// refetch the authRecord and refresh its tokenKey
|
||||
authRecord2, err := testApp.FindAuthRecordByEmail("users", "test@example.com")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
authRecord2.RefreshTokenKey()
|
||||
|
||||
err = testApp.Save(authRecord2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
clientAuthRecord, _ := client.Get(apis.RealtimeClientAuthKey).(*core.Record)
|
||||
if clientAuthRecord != nil {
|
||||
t.Fatalf("Expected authRecord to be unset, got %q", clientAuthRecord.Email())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRealtimeAuthRecordUnsetOnCollectionSecretChange(t *testing.T) {
|
||||
testApp, _ := tests.NewTestApp()
|
||||
defer testApp.Cleanup()
|
||||
|
||||
// init realtime handlers
|
||||
_, err := apis.NewRouter(testApp)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
usersCollection, err := testApp.FindCollectionByNameOrId("users")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
clientsCollection, err := testApp.FindCollectionByNameOrId("clients")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
authRecord1, err := testApp.FindAuthRecordByEmail(usersCollection, "test@example.com")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client1 := subscriptions.NewDefaultClient()
|
||||
client1.Set(apis.RealtimeClientAuthKey, authRecord1)
|
||||
|
||||
authRecord2, err := testApp.FindAuthRecordByEmail(usersCollection, "test@example.com")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client2 := subscriptions.NewDefaultClient()
|
||||
client2.Set(apis.RealtimeClientAuthKey, authRecord2)
|
||||
|
||||
authRecord3, err := testApp.FindAuthRecordByEmail(clientsCollection, "test@example.com")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client3 := subscriptions.NewDefaultClient()
|
||||
client3.Set(apis.RealtimeClientAuthKey, authRecord3)
|
||||
|
||||
clientMocks := map[*core.Record]subscriptions.Client{
|
||||
authRecord1: client1,
|
||||
authRecord2: client2,
|
||||
authRecord3: client3,
|
||||
}
|
||||
for _, client := range clientMocks {
|
||||
testApp.SubscriptionsBroker().Register(client)
|
||||
}
|
||||
|
||||
// change the secret of the users collection (should trigger unset)
|
||||
usersCollection.AuthToken.Secret = strings.Repeat("a", 30)
|
||||
err = testApp.Save(usersCollection)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// change something else of the clients collection (shouldn't trigger unset)
|
||||
clientsCollection.ListRule = nil
|
||||
err = testApp.Save(clientsCollection)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
expectations := map[*core.Record]bool{
|
||||
// record -> unset
|
||||
authRecord1: true,
|
||||
authRecord2: true,
|
||||
authRecord3: false,
|
||||
}
|
||||
for record, expectedUnset := range expectations {
|
||||
clientAuthRecord, _ := clientMocks[record].Get(apis.RealtimeClientAuthKey).(*core.Record)
|
||||
unset := clientAuthRecord == nil
|
||||
if unset != expectedUnset {
|
||||
t.Fatalf("Expected unset state %v, got %v (%v)", expectedUnset, unset, clientAuthRecord)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRealtimeAuthRecordUnsetOnCollectionDelete(t *testing.T) {
|
||||
testApp, _ := tests.NewTestApp()
|
||||
defer testApp.Cleanup()
|
||||
|
||||
// init realtime handlers
|
||||
_, err := apis.NewRouter(testApp)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
usersCollection, err := testApp.FindCollectionByNameOrId("users")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
clientsCollection, err := testApp.FindCollectionByNameOrId("clients")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
authRecord1, err := testApp.FindAuthRecordByEmail(usersCollection, "test@example.com")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client1 := subscriptions.NewDefaultClient()
|
||||
client1.Set(apis.RealtimeClientAuthKey, authRecord1)
|
||||
|
||||
authRecord2, err := testApp.FindAuthRecordByEmail(usersCollection, "test@example.com")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client2 := subscriptions.NewDefaultClient()
|
||||
client2.Set(apis.RealtimeClientAuthKey, authRecord2)
|
||||
|
||||
authRecord3, err := testApp.FindAuthRecordByEmail(clientsCollection, "test@example.com")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client3 := subscriptions.NewDefaultClient()
|
||||
client3.Set(apis.RealtimeClientAuthKey, authRecord3)
|
||||
|
||||
clientMocks := map[*core.Record]subscriptions.Client{
|
||||
authRecord1: client1,
|
||||
authRecord2: client2,
|
||||
authRecord3: client3,
|
||||
}
|
||||
for _, client := range clientMocks {
|
||||
testApp.SubscriptionsBroker().Register(client)
|
||||
}
|
||||
|
||||
// mock users collection delete event to avoid triggering constraints check
|
||||
e := new(core.ModelEvent)
|
||||
e.App = testApp
|
||||
e.Type = core.ModelEventTypeDelete
|
||||
e.Context = context.Background()
|
||||
e.Model = usersCollection
|
||||
|
||||
err = testApp.OnModelAfterDeleteSuccess().Trigger(e)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
expectations := map[*core.Record]bool{
|
||||
// record -> unset
|
||||
authRecord1: true,
|
||||
authRecord2: true,
|
||||
authRecord3: false,
|
||||
}
|
||||
for record, expectedUnset := range expectations {
|
||||
clientAuthRecord, _ := clientMocks[record].Get(apis.RealtimeClientAuthKey).(*core.Record)
|
||||
unset := clientAuthRecord == nil
|
||||
if unset != expectedUnset {
|
||||
t.Fatalf("Expected unset state %v, got %v (%v)", expectedUnset, unset, clientAuthRecord)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -551,7 +899,10 @@ func TestRealtimeCustomAuthModelDeleteEvent(t *testing.T) {
|
||||
defer testApp.Cleanup()
|
||||
|
||||
// init realtime handlers
|
||||
apis.NewRouter(testApp)
|
||||
_, err := apis.NewRouter(testApp)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
authRecord1, err := testApp.FindAuthRecordByEmail("users", "test@example.com")
|
||||
if err != nil {
|
||||
@@ -608,7 +959,10 @@ func TestRealtimeCustomAuthModelUpdateEvent(t *testing.T) {
|
||||
defer testApp.Cleanup()
|
||||
|
||||
// init realtime handlers
|
||||
apis.NewRouter(testApp)
|
||||
_, err := apis.NewRouter(testApp)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
authRecord, err := testApp.FindAuthRecordByEmail("users", "test@example.com")
|
||||
if err != nil {
|
||||
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
package apis
|
||||
|
||||
import (
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/router"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/router"
|
||||
)
|
||||
|
||||
// bindRecordAuthApi registers the auth record api endpoints and
|
||||
|
||||
@@ -3,9 +3,9 @@ package apis
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
validation "github.com/go-ozzo/ozzo-validation/v4"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/security"
|
||||
validation "github.com/pocketbase/ozzo-validation/v4"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/security"
|
||||
)
|
||||
|
||||
func recordConfirmEmailChange(e *core.RequestEvent) error {
|
||||
|
||||
@@ -5,8 +5,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
)
|
||||
|
||||
func TestRecordConfirmEmailChange(t *testing.T) {
|
||||
|
||||
@@ -3,10 +3,10 @@ package apis
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
validation "github.com/go-ozzo/ozzo-validation/v4"
|
||||
"github.com/go-ozzo/ozzo-validation/v4/is"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/mails"
|
||||
validation "github.com/pocketbase/ozzo-validation/v4"
|
||||
"github.com/pocketbase/ozzo-validation/v4/is"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/mails"
|
||||
)
|
||||
|
||||
func recordRequestEmailChange(e *core.RequestEvent) error {
|
||||
|
||||
@@ -5,8 +5,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
)
|
||||
|
||||
func TestRecordRequestEmailChange(t *testing.T) {
|
||||
|
||||
@@ -3,8 +3,8 @@ package apis
|
||||
import (
|
||||
"time"
|
||||
|
||||
validation "github.com/go-ozzo/ozzo-validation/v4"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
validation "github.com/pocketbase/ozzo-validation/v4"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
)
|
||||
|
||||
// note: for now allow superusers but it may change in the future to allow access
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
)
|
||||
|
||||
func TestRecordAuthImpersonate(t *testing.T) {
|
||||
|
||||
@@ -5,9 +5,9 @@ import (
|
||||
"net/http"
|
||||
"slices"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/auth"
|
||||
"github.com/pocketbase/pocketbase/tools/security"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/auth"
|
||||
"github.com/tabshift-gh/pocketbase/tools/security"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
|
||||
@@ -4,8 +4,8 @@ import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
)
|
||||
|
||||
func TestRecordAuthMethodsList(t *testing.T) {
|
||||
|
||||
@@ -6,12 +6,12 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
validation "github.com/go-ozzo/ozzo-validation/v4"
|
||||
"github.com/go-ozzo/ozzo-validation/v4/is"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/mails"
|
||||
"github.com/pocketbase/pocketbase/tools/routine"
|
||||
"github.com/pocketbase/pocketbase/tools/security"
|
||||
validation "github.com/pocketbase/ozzo-validation/v4"
|
||||
"github.com/pocketbase/ozzo-validation/v4/is"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/mails"
|
||||
"github.com/tabshift-gh/pocketbase/tools/routine"
|
||||
"github.com/tabshift-gh/pocketbase/tools/security"
|
||||
)
|
||||
|
||||
func recordRequestOTP(e *core.RequestEvent) error {
|
||||
|
||||
@@ -7,9 +7,9 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/tools/types"
|
||||
)
|
||||
|
||||
func TestRecordRequestOTP(t *testing.T) {
|
||||
|
||||
@@ -3,10 +3,10 @@ package apis
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
validation "github.com/go-ozzo/ozzo-validation/v4"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/core/validators"
|
||||
"github.com/pocketbase/pocketbase/tools/security"
|
||||
validation "github.com/pocketbase/ozzo-validation/v4"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/core/validators"
|
||||
"github.com/tabshift-gh/pocketbase/tools/security"
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
|
||||
|
||||
@@ -5,8 +5,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
)
|
||||
|
||||
func TestRecordConfirmPasswordReset(t *testing.T) {
|
||||
|
||||
@@ -6,11 +6,11 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
validation "github.com/go-ozzo/ozzo-validation/v4"
|
||||
"github.com/go-ozzo/ozzo-validation/v4/is"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/mails"
|
||||
"github.com/pocketbase/pocketbase/tools/routine"
|
||||
validation "github.com/pocketbase/ozzo-validation/v4"
|
||||
"github.com/pocketbase/ozzo-validation/v4/is"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/mails"
|
||||
"github.com/tabshift-gh/pocketbase/tools/routine"
|
||||
)
|
||||
|
||||
func recordRequestPasswordReset(e *core.RequestEvent) error {
|
||||
|
||||
@@ -6,8 +6,8 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
)
|
||||
|
||||
func TestRecordRequestPasswordReset(t *testing.T) {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package apis
|
||||
|
||||
import (
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/security"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/security"
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
|
||||
|
||||
@@ -4,8 +4,8 @@ import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
)
|
||||
|
||||
func TestRecordAuthRefresh(t *testing.T) {
|
||||
|
||||
@@ -3,9 +3,9 @@ package apis
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
validation "github.com/go-ozzo/ozzo-validation/v4"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/security"
|
||||
validation "github.com/pocketbase/ozzo-validation/v4"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/security"
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
|
||||
@@ -45,6 +45,13 @@ func recordConfirmVerification(e *core.RequestEvent) error {
|
||||
if !wasVerified {
|
||||
e.Record.SetVerified(true)
|
||||
|
||||
// similar to the OTP auth, we enforce an extra password reset
|
||||
// guard as this way is less prone to pre-hijacking attacks
|
||||
// in case the password auth is eventually enabled later
|
||||
if !e.Record.Collection().PasswordAuth.Enabled {
|
||||
e.Record.SetRandomPassword()
|
||||
}
|
||||
|
||||
if err := e.App.Save(e.Record); err != nil {
|
||||
return firstApiError(err, e.BadRequestError("An error occurred while saving the verified state.", err))
|
||||
}
|
||||
|
||||
@@ -5,8 +5,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
)
|
||||
|
||||
func TestRecordConfirmVerification(t *testing.T) {
|
||||
@@ -120,7 +120,7 @@ func TestRecordConfirmVerification(t *testing.T) {
|
||||
}
|
||||
|
||||
if user.Verified() {
|
||||
t.Fatalf("Expected the user to be unverified before the confirmation")
|
||||
t.Fatal("Expected the user to be unverified before the confirmation")
|
||||
}
|
||||
|
||||
// ensure that there is at least one pre-existing OAuth2 link
|
||||
@@ -152,6 +152,85 @@ func TestRecordConfirmVerification(t *testing.T) {
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "valid token (disabled password auth)",
|
||||
Method: http.MethodPost,
|
||||
URL: "/api/collections/users/confirm-verification",
|
||||
Body: strings.NewReader(`{
|
||||
"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsImV4cCI6MjUyNDYwNDQ2MSwidHlwZSI6InZlcmlmaWNhdGlvbiIsImNvbGxlY3Rpb25JZCI6Il9wYl91c2Vyc19hdXRoXyIsImVtYWlsIjoidGVzdEBleGFtcGxlLmNvbSJ9.SetHpu2H-x-q4TIUz-xiQjwi7MNwLCLvSs4O0hUSp0E"
|
||||
}`),
|
||||
ExpectedStatus: 204,
|
||||
ExpectedEvents: map[string]int{
|
||||
"*": 0,
|
||||
"OnRecordConfirmVerificationRequest": 1,
|
||||
"OnModelUpdate": 1,
|
||||
"OnModelValidate": 1,
|
||||
"OnModelUpdateExecute": 1,
|
||||
"OnModelAfterUpdateSuccess": 1,
|
||||
"OnRecordUpdate": 1,
|
||||
"OnRecordValidate": 1,
|
||||
"OnRecordUpdateExecute": 1,
|
||||
"OnRecordAfterUpdateSuccess": 1,
|
||||
// unverified->verified external auths removal
|
||||
"OnModelDelete": 2,
|
||||
"OnModelDeleteExecute": 2,
|
||||
"OnModelAfterDeleteSuccess": 2,
|
||||
"OnRecordDelete": 2,
|
||||
"OnRecordDeleteExecute": 2,
|
||||
"OnRecordAfterDeleteSuccess": 2,
|
||||
},
|
||||
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
|
||||
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
user.Collection().PasswordAuth.Enabled = false
|
||||
if err = app.Save(user.Collection()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if user.Verified() {
|
||||
t.Fatal("Expected the user to be unverified before the confirmation")
|
||||
}
|
||||
|
||||
if !user.ValidatePassword("1234567890") {
|
||||
t.Fatal("Expected password to be valid")
|
||||
}
|
||||
|
||||
// ensure that there is at least one pre-existing OAuth2 link
|
||||
externalAuths, err := app.FindAllExternalAuthsByRecord(user)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(externalAuths) == 0 {
|
||||
t.Fatal("Expected at least one external auths")
|
||||
}
|
||||
},
|
||||
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
|
||||
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !user.Verified() {
|
||||
t.Fatalf("Expected the user to be verified after the confirmation")
|
||||
}
|
||||
|
||||
if user.ValidatePassword("1234567890") {
|
||||
t.Fatal("Expected the user password to be reset")
|
||||
}
|
||||
|
||||
// ensure that all pre-existing OAuth2 links are cleared
|
||||
externalAuths, err := app.FindAllExternalAuthsByRecord(user)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(externalAuths) > 0 {
|
||||
t.Fatalf("Expected all external auths to be cleared, found %d", len(externalAuths))
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "valid token (already verified)",
|
||||
Method: http.MethodPost,
|
||||
|
||||
@@ -6,11 +6,11 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
validation "github.com/go-ozzo/ozzo-validation/v4"
|
||||
"github.com/go-ozzo/ozzo-validation/v4/is"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/mails"
|
||||
"github.com/pocketbase/pocketbase/tools/routine"
|
||||
validation "github.com/pocketbase/ozzo-validation/v4"
|
||||
"github.com/pocketbase/ozzo-validation/v4/is"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/mails"
|
||||
"github.com/tabshift-gh/pocketbase/tools/routine"
|
||||
)
|
||||
|
||||
func recordRequestVerification(e *core.RequestEvent) error {
|
||||
|
||||
@@ -6,8 +6,8 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
)
|
||||
|
||||
func TestRecordRequestVerification(t *testing.T) {
|
||||
|
||||
@@ -17,13 +17,13 @@ import (
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
validation "github.com/go-ozzo/ozzo-validation/v4"
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/auth"
|
||||
"github.com/pocketbase/pocketbase/tools/dbutils"
|
||||
"github.com/pocketbase/pocketbase/tools/filesystem"
|
||||
"github.com/pocketbase/pocketbase/tools/inflector"
|
||||
validation "github.com/pocketbase/ozzo-validation/v4"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/auth"
|
||||
"github.com/tabshift-gh/pocketbase/tools/dbutils"
|
||||
"github.com/tabshift-gh/pocketbase/tools/filesystem"
|
||||
"github.com/tabshift-gh/pocketbase/tools/inflector"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
@@ -203,7 +203,6 @@ func (form *recordOAuth2LoginForm) validate() error {
|
||||
return validation.ValidateStruct(form,
|
||||
validation.Field(&form.Provider, validation.Required, validation.Length(0, 100), validation.By(form.checkProviderName)),
|
||||
validation.Field(&form.Code, validation.Required),
|
||||
validation.Field(&form.RedirectURL, validation.Required),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -7,9 +7,9 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/subscriptions"
|
||||
"github.com/pocketbase/pocketbase/ui"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/subscriptions"
|
||||
"github.com/tabshift-gh/pocketbase/ui"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -55,8 +55,18 @@ func oauth2SubscriptionRedirect(e *core.RequestEvent) error {
|
||||
}
|
||||
defer client.Unsubscribe(oauth2SubscriptionTopic)
|
||||
|
||||
// additional check to minimize the risk of XSRF attack vectors
|
||||
//
|
||||
// note: custom registered clients (aka. those without IP in the store)
|
||||
// are excluded from the check for backward compatibility
|
||||
clientIP, _ := client.Get(RealtimeClientIPKey).(string)
|
||||
if clientIP != "" && clientIP != e.RealIP() {
|
||||
e.App.Logger().Debug("The client IP that completed the authentication is different from the one that initialized the OAuth2 realtime connection")
|
||||
return failureRedirect(e)
|
||||
}
|
||||
|
||||
// temporary store the Apple user's name so that it can be later retrieved with the authWithOAuth2 call
|
||||
// (see https://github.com/pocketbase/pocketbase/issues/7090)
|
||||
// (see https://github.com/tabshift-gh/pocketbase/issues/7090)
|
||||
if data.AppleUser != "" && data.Error == "" && data.Code != "" {
|
||||
nameErr := parseAndStoreAppleRedirectName(
|
||||
e.App,
|
||||
|
||||
@@ -8,17 +8,18 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/pocketbase/pocketbase/tools/subscriptions"
|
||||
"github.com/tabshift-gh/pocketbase/apis"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/tools/subscriptions"
|
||||
)
|
||||
|
||||
func TestRecordAuthWithOAuth2Redirect(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
clientStubs := make([]map[string]subscriptions.Client, 0, 10)
|
||||
clientStubs := make([]map[string]subscriptions.Client, 0, 11)
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
for i := 0; i < 11; i++ {
|
||||
c1 := subscriptions.NewDefaultClient()
|
||||
|
||||
c2 := subscriptions.NewDefaultClient()
|
||||
@@ -335,6 +336,28 @@ func TestRecordAuthWithOAuth2Redirect(t *testing.T) {
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "client with different IP",
|
||||
Method: http.MethodGet,
|
||||
URL: "/api/oauth2-redirect?code=123&state=" + clientStubs[10]["c3"].Id(),
|
||||
Headers: map[string]string{"x-test-ip": "127.0.0.2"},
|
||||
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
|
||||
app.Settings().TrustedProxy.Headers = []string{"x-test-ip"}
|
||||
|
||||
clientStubs[10]["c3"].Set(apis.RealtimeClientIPKey, "127.0.0.1")
|
||||
|
||||
beforeTestFunc(clientStubs[10], map[string][]string{
|
||||
"c3": {`"state":"` + clientStubs[10]["c3"].Id(), `"code":"123"`},
|
||||
})(t, app, e)
|
||||
},
|
||||
ExpectedStatus: http.StatusTemporaryRedirect,
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
|
||||
app.Store().Get("cancelFunc").(context.CancelFunc)()
|
||||
|
||||
checkFailureRedirect(t, app, res)
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, scenario := range scenarios {
|
||||
|
||||
@@ -11,10 +11,10 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/pocketbase/pocketbase/tools/auth"
|
||||
"github.com/pocketbase/pocketbase/tools/dbutils"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/tools/auth"
|
||||
"github.com/tabshift-gh/pocketbase/tools/dbutils"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
@@ -90,10 +90,11 @@ func TestRecordAuthWithOAuth2(t *testing.T) {
|
||||
`"data":{`,
|
||||
`"provider":`,
|
||||
`"code":`,
|
||||
`"redirectURL":`,
|
||||
},
|
||||
NotExpectedContent: []string{
|
||||
`"codeVerifier":`, // should be optional
|
||||
// should be optional
|
||||
`"codeVerifier":`,
|
||||
`"redirectURL":`,
|
||||
},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
},
|
||||
@@ -109,10 +110,11 @@ func TestRecordAuthWithOAuth2(t *testing.T) {
|
||||
`"data":{`,
|
||||
`"provider":`,
|
||||
`"code":`,
|
||||
`"redirectURL":`,
|
||||
},
|
||||
NotExpectedContent: []string{
|
||||
`"codeVerifier":`, // should be optional
|
||||
// should be optional
|
||||
`"codeVerifier":`,
|
||||
`"redirectURL":`,
|
||||
},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
},
|
||||
|
||||
@@ -4,8 +4,8 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
validation "github.com/go-ozzo/ozzo-validation/v4"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
validation "github.com/pocketbase/ozzo-validation/v4"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
)
|
||||
|
||||
func recordAuthWithOTP(e *core.RequestEvent) error {
|
||||
@@ -68,7 +68,7 @@ func recordAuthWithOTP(e *core.RequestEvent) error {
|
||||
otpId := e.OTP.Id
|
||||
otpSentTo := e.OTP.SentTo()
|
||||
|
||||
// eagerly delete the OTP to avoid unnecessery double delete model hook calls
|
||||
// eagerly delete the OTP to avoid unnecessary double delete model hook calls
|
||||
// triggered by the password change below
|
||||
err := e.App.Delete(e.OTP)
|
||||
if err != nil {
|
||||
|
||||
@@ -5,9 +5,9 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/tools/types"
|
||||
)
|
||||
|
||||
func TestRecordAuthWithOTP(t *testing.T) {
|
||||
|
||||
@@ -6,12 +6,12 @@ import (
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
validation "github.com/go-ozzo/ozzo-validation/v4"
|
||||
"github.com/go-ozzo/ozzo-validation/v4/is"
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/dbutils"
|
||||
"github.com/pocketbase/pocketbase/tools/list"
|
||||
validation "github.com/pocketbase/ozzo-validation/v4"
|
||||
"github.com/pocketbase/ozzo-validation/v4/is"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/dbutils"
|
||||
"github.com/tabshift-gh/pocketbase/tools/list"
|
||||
)
|
||||
|
||||
func recordAuthWithPassword(e *core.RequestEvent) error {
|
||||
|
||||
@@ -5,9 +5,9 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/pocketbase/pocketbase/tools/dbutils"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/tools/dbutils"
|
||||
)
|
||||
|
||||
func TestRecordAuthWithPassword(t *testing.T) {
|
||||
|
||||
+8
-8
@@ -10,14 +10,14 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/forms"
|
||||
"github.com/pocketbase/pocketbase/tools/filesystem"
|
||||
"github.com/pocketbase/pocketbase/tools/inflector"
|
||||
"github.com/pocketbase/pocketbase/tools/list"
|
||||
"github.com/pocketbase/pocketbase/tools/router"
|
||||
"github.com/pocketbase/pocketbase/tools/search"
|
||||
"github.com/pocketbase/pocketbase/tools/security"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/forms"
|
||||
"github.com/tabshift-gh/pocketbase/tools/filesystem"
|
||||
"github.com/tabshift-gh/pocketbase/tools/inflector"
|
||||
"github.com/tabshift-gh/pocketbase/tools/list"
|
||||
"github.com/tabshift-gh/pocketbase/tools/router"
|
||||
"github.com/tabshift-gh/pocketbase/tools/search"
|
||||
"github.com/tabshift-gh/pocketbase/tools/security"
|
||||
)
|
||||
|
||||
// bindRecordCrudApi registers the record crud api endpoints and
|
||||
|
||||
@@ -5,8 +5,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
)
|
||||
|
||||
func TestRecordCrudAuthOriginList(t *testing.T) {
|
||||
|
||||
@@ -5,8 +5,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
)
|
||||
|
||||
func TestRecordCrudExternalAuthList(t *testing.T) {
|
||||
|
||||
@@ -5,8 +5,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
)
|
||||
|
||||
func TestRecordCrudMFAList(t *testing.T) {
|
||||
|
||||
@@ -5,8 +5,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
)
|
||||
|
||||
func TestRecordCrudOTPList(t *testing.T) {
|
||||
|
||||
@@ -6,8 +6,8 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
)
|
||||
|
||||
func TestRecordCrudSuperuserList(t *testing.T) {
|
||||
|
||||
@@ -11,11 +11,11 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/apis"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/pocketbase/pocketbase/tools/router"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
"github.com/tabshift-gh/pocketbase/apis"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/tools/router"
|
||||
"github.com/tabshift-gh/pocketbase/tools/types"
|
||||
)
|
||||
|
||||
func TestRecordCrudList(t *testing.T) {
|
||||
|
||||
+14
-7
@@ -9,13 +9,13 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/mails"
|
||||
"github.com/pocketbase/pocketbase/tools/router"
|
||||
"github.com/pocketbase/pocketbase/tools/routine"
|
||||
"github.com/pocketbase/pocketbase/tools/search"
|
||||
"github.com/pocketbase/pocketbase/tools/security"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/mails"
|
||||
"github.com/tabshift-gh/pocketbase/tools/router"
|
||||
"github.com/tabshift-gh/pocketbase/tools/routine"
|
||||
"github.com/tabshift-gh/pocketbase/tools/search"
|
||||
"github.com/tabshift-gh/pocketbase/tools/security"
|
||||
"github.com/tabshift-gh/pocketbase/tools/types"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -43,6 +43,13 @@ func RecordAuthResponse(e *core.RequestEvent, authRecord *core.Record, authMetho
|
||||
}
|
||||
|
||||
func recordAuthResponse(e *core.RequestEvent, authRecord *core.Record, token string, authMethod string, meta any) error {
|
||||
if authRecord.IsSuperuser() {
|
||||
allowedIPs := e.App.Settings().SuperuserIPs
|
||||
if len(allowedIPs) > 0 && !isIPInList(allowedIPs, e.RealIP()) {
|
||||
return e.ForbiddenError("", errors.New("superuser IP is not whitelisted"))
|
||||
}
|
||||
}
|
||||
|
||||
originalRequestInfo, err := e.RequestInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -9,11 +9,11 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/apis"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/pocketbase/pocketbase/tools/router"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
"github.com/tabshift-gh/pocketbase/apis"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/tools/router"
|
||||
"github.com/tabshift-gh/pocketbase/tools/types"
|
||||
)
|
||||
|
||||
func TestEnrichRecords(t *testing.T) {
|
||||
@@ -759,3 +759,39 @@ func TestRecordAuthResponseMFACheck(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRecordAuthResponseSuperuserIPsWhitelistCheck(t *testing.T) {
|
||||
app, _ := tests.NewTestApp()
|
||||
defer app.Cleanup()
|
||||
|
||||
superuser, err := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test@example.com")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
app.Settings().TrustedProxy.Headers = []string{"x-test-ip"}
|
||||
|
||||
event := new(core.RequestEvent)
|
||||
event.App = app
|
||||
event.Request = httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
event.Request.Header.Set("x-test-ip", "127.0.0.1")
|
||||
event.Response = httptest.NewRecorder()
|
||||
|
||||
t.Run("non-whitelisted", func(t *testing.T) {
|
||||
app.Settings().SuperuserIPs = []string{"0.0.0.0"}
|
||||
|
||||
err = apis.RecordAuthResponse(event, superuser, "example", nil)
|
||||
if err == nil {
|
||||
t.Fatal("Expected response error, got nil")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("whitelisted", func(t *testing.T) {
|
||||
app.Settings().SuperuserIPs = []string{"0.0.0.0", "127.0.0.1"}
|
||||
|
||||
err = apis.RecordAuthResponse(event, superuser, "example", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+6
-6
@@ -13,16 +13,16 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/hook"
|
||||
"github.com/pocketbase/pocketbase/tools/list"
|
||||
"github.com/pocketbase/pocketbase/tools/routine"
|
||||
"github.com/pocketbase/pocketbase/ui"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/hook"
|
||||
"github.com/tabshift-gh/pocketbase/tools/list"
|
||||
"github.com/tabshift-gh/pocketbase/tools/routine"
|
||||
"github.com/tabshift-gh/pocketbase/ui"
|
||||
"golang.org/x/crypto/acme"
|
||||
"golang.org/x/crypto/acme/autocert"
|
||||
)
|
||||
|
||||
const defaultCSP = "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' http://127.0.0.1:* https://tile.openstreetmap.org data: blob:; connect-src 'self' http://127.0.0.1:* https://nominatim.openstreetmap.org; script-src 'self' http://127.0.0.1:*; frame-src 'none'"
|
||||
const defaultCSP = "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' http://127.0.0.1:* https://tile.openstreetmap.org data: blob:; connect-src 'self' http://127.0.0.1:* https://nominatim.openstreetmap.org; script-src 'self' http://127.0.0.1:*; frame-ancestors 'none'"
|
||||
|
||||
// ServeConfig defines a configuration struct for apis.Serve().
|
||||
type ServeConfig struct {
|
||||
|
||||
+4
-4
@@ -3,10 +3,10 @@ package apis
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
validation "github.com/go-ozzo/ozzo-validation/v4"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/forms"
|
||||
"github.com/pocketbase/pocketbase/tools/router"
|
||||
validation "github.com/pocketbase/ozzo-validation/v4"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/forms"
|
||||
"github.com/tabshift-gh/pocketbase/tools/router"
|
||||
)
|
||||
|
||||
// bindSettingsApi registers the settings api endpoints.
|
||||
|
||||
@@ -11,8 +11,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
)
|
||||
|
||||
func TestSettingsList(t *testing.T) {
|
||||
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
package apis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
validation "github.com/pocketbase/ozzo-validation/v4"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/router"
|
||||
)
|
||||
|
||||
const (
|
||||
runSQLMaxRows = 1000
|
||||
runSQLMaxTimeout = 3 * time.Minute
|
||||
)
|
||||
|
||||
// bindSQLApi registers the SQL api endpoints.
|
||||
func bindSQLApi(app core.App, rg *router.RouterGroup[*core.RequestEvent]) {
|
||||
subGroup := rg.Group("/sql").Bind(RequireSuperuserAuth())
|
||||
subGroup.POST("", runSQL)
|
||||
}
|
||||
|
||||
func runSQL(e *core.RequestEvent) error {
|
||||
// extra precaution in case manually invoked from somewhere else
|
||||
if !e.HasSuperuserAuth() {
|
||||
return e.ForbiddenError("", nil)
|
||||
}
|
||||
|
||||
form := runSQLForm{}
|
||||
|
||||
err := e.BindBody(&form)
|
||||
if err != nil {
|
||||
return firstApiError(err, e.BadRequestError("An error occurred while loading the submitted data.", err))
|
||||
}
|
||||
|
||||
err = form.validate()
|
||||
if err != nil {
|
||||
return firstApiError(err, e.BadRequestError("An error occurred while validating the submitted data.", err))
|
||||
}
|
||||
|
||||
result, err := executeQuery(e.App, form.Query, runSQLMaxRows)
|
||||
if err != nil {
|
||||
return firstApiError(err, e.BadRequestError("Failed to execute query. Raw error:\n"+err.Error(), nil))
|
||||
}
|
||||
|
||||
return e.JSON(http.StatusOK, result)
|
||||
}
|
||||
|
||||
type runSQLForm struct {
|
||||
Query string `form:"query" json:"query"`
|
||||
}
|
||||
|
||||
func (form *runSQLForm) validate() error {
|
||||
return validation.ValidateStruct(form,
|
||||
validation.Field(&form.Query, validation.Required, validation.Length(0, 5000)),
|
||||
)
|
||||
}
|
||||
|
||||
type runSQLResultColumn struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Nullable bool `json:"nullable"`
|
||||
}
|
||||
|
||||
type runSQLResult struct {
|
||||
ExecTime int64 `json:"execTime"`
|
||||
AffectedRows int64 `json:"affectedRows"`
|
||||
Columns []runSQLResultColumn `json:"columns"`
|
||||
Rows [][]any `json:"rows"`
|
||||
}
|
||||
|
||||
var knownWriteQueryPrefixes = []string{
|
||||
"INSERT", "CREATE", "UPDATE", "DELETE",
|
||||
"DROP", "DETACH", "ALTER", "REPLACE",
|
||||
}
|
||||
|
||||
func executeQuery(app core.App, query string, maxRows int) (*runSQLResult, error) {
|
||||
query = strings.TrimSpace(query)
|
||||
if query == "" {
|
||||
// see https://github.com/mattn/go-sqlite3/issues/950
|
||||
return nil, errors.New("empty query")
|
||||
}
|
||||
|
||||
var isPossibleWriteQuery bool
|
||||
|
||||
// loosely check the query type
|
||||
ucQuery := strings.ToUpper(query)
|
||||
if !strings.HasPrefix(ucQuery, "SELECT") {
|
||||
for _, prefix := range knownWriteQueryPrefixes {
|
||||
if strings.HasPrefix(ucQuery, prefix) {
|
||||
isPossibleWriteQuery = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// note: don't extend the request context to minimize the risk of
|
||||
// causing integrity issues with custom non-transaction mutations
|
||||
ctx, cancelFunc := context.WithTimeout(context.Background(), runSQLMaxTimeout)
|
||||
defer cancelFunc()
|
||||
|
||||
result := &runSQLResult{
|
||||
// init empty slices to ensure "[]" serialization
|
||||
Columns: []runSQLResultColumn{},
|
||||
Rows: [][]any{},
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
defer func() {
|
||||
result.ExecTime = time.Since(now).Milliseconds()
|
||||
}()
|
||||
|
||||
// assume write/mutation query
|
||||
// ---------------------------------------------------------------
|
||||
if isPossibleWriteQuery {
|
||||
// auto wrap in transaction in case there are multiple inline queries
|
||||
txErr := app.RunInTransaction(func(txApp core.App) error {
|
||||
execResult, err := txApp.NonconcurrentDB().NewQuery(query).WithContext(ctx).Execute()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
result.AffectedRows, err = execResult.RowsAffected()
|
||||
if err != nil {
|
||||
// non-critical error (e.g. not supported by the driver)
|
||||
txApp.Logger().Debug("Unable to fetch affected rows", slog.String("error", err.Error()))
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if txErr != nil {
|
||||
return nil, txErr
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// assume query returning rows
|
||||
// ---------------------------------------------------------------
|
||||
rows, err := app.ConcurrentDB().NewQuery(query).WithContext(ctx).Rows()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
// populate columns info
|
||||
// ---
|
||||
colTypes, err := rows.ColumnTypes()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, colType := range colTypes {
|
||||
col := runSQLResultColumn{
|
||||
Name: colType.Name(),
|
||||
Type: colType.DatabaseTypeName(),
|
||||
}
|
||||
col.Nullable, _ = colType.Nullable()
|
||||
|
||||
result.Columns = append(result.Columns, col)
|
||||
}
|
||||
|
||||
// populate rows
|
||||
// ---
|
||||
for rows.Next() {
|
||||
if len(result.Rows) >= maxRows {
|
||||
break
|
||||
}
|
||||
|
||||
rowData := make([]any, len(colTypes))
|
||||
for i := 0; i < len(colTypes); i++ {
|
||||
var v *string
|
||||
rowData[i] = &v
|
||||
}
|
||||
|
||||
err := rows.Scan(rowData...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result.Rows = append(result.Rows, rowData)
|
||||
}
|
||||
|
||||
err = rows.Err()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package apis_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
)
|
||||
|
||||
func TestSQLRun(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
scenarios := []tests.ApiScenario{
|
||||
{
|
||||
Name: "guest",
|
||||
Method: http.MethodPost,
|
||||
URL: "/api/sql",
|
||||
Body: strings.NewReader(`{"query":"select 1"}`),
|
||||
ExpectedStatus: 401,
|
||||
ExpectedContent: []string{`"data":{}`},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
},
|
||||
{
|
||||
Name: "regular user",
|
||||
Method: http.MethodPost,
|
||||
URL: "/api/sql",
|
||||
Body: strings.NewReader(`{"query":"select 1"}`),
|
||||
Headers: map[string]string{
|
||||
// users, test2@example.com
|
||||
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6Im9hcDY0MGNvdDR5cnUycyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.GfJo6EHIobgas_AXt-M-tj5IoQendPnrkMSe9ExuSEY",
|
||||
},
|
||||
ExpectedStatus: 403,
|
||||
ExpectedContent: []string{`"data":{}`},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
},
|
||||
{
|
||||
Name: "superuser",
|
||||
Method: http.MethodPost,
|
||||
URL: "/api/sql",
|
||||
Body: strings.NewReader(`{"query":"select 1"}`),
|
||||
Headers: map[string]string{
|
||||
// superusers, test@example.com
|
||||
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
|
||||
},
|
||||
ExpectedStatus: 200,
|
||||
ExpectedContent: []string{
|
||||
`"execTime":`,
|
||||
`"affectedRows":0`,
|
||||
`"columns":[{"name":"1","type":"","nullable":true}]`,
|
||||
`"rows":[["1"]]`,
|
||||
},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
},
|
||||
{
|
||||
Name: "empty query",
|
||||
Method: http.MethodPost,
|
||||
URL: "/api/sql",
|
||||
Body: strings.NewReader(`{"query":""}`),
|
||||
Headers: map[string]string{
|
||||
// superusers, test@example.com
|
||||
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
|
||||
},
|
||||
ExpectedStatus: 400,
|
||||
ExpectedContent: []string{
|
||||
`"data":{`,
|
||||
`"query":{`,
|
||||
},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
},
|
||||
{
|
||||
Name: "invalid query",
|
||||
Method: http.MethodPost,
|
||||
URL: "/api/sql",
|
||||
Body: strings.NewReader(`{"query":"invalid"}`),
|
||||
Headers: map[string]string{
|
||||
// superusers, test@example.com
|
||||
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
|
||||
},
|
||||
ExpectedStatus: 400,
|
||||
ExpectedContent: []string{
|
||||
`"data":{}`,
|
||||
`Raw error:`,
|
||||
`SQL logic error`,
|
||||
},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
},
|
||||
{
|
||||
Name: "query with length above the limit",
|
||||
Method: http.MethodPost,
|
||||
URL: "/api/sql",
|
||||
Body: strings.NewReader(`{"query":"` + strings.Repeat("a", 5001) + `"}`),
|
||||
Headers: map[string]string{
|
||||
// superusers, test@example.com
|
||||
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
|
||||
},
|
||||
ExpectedStatus: 400,
|
||||
ExpectedContent: []string{
|
||||
`"data":{`,
|
||||
`"query":{`,
|
||||
},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
},
|
||||
{
|
||||
Name: "query with length equal to the limit",
|
||||
Method: http.MethodPost,
|
||||
URL: "/api/sql",
|
||||
Body: strings.NewReader(`{"query":"select '` + strings.Repeat("a", 4985) + `' as id"}`),
|
||||
Headers: map[string]string{
|
||||
// superusers, test@example.com
|
||||
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
|
||||
},
|
||||
ExpectedStatus: 200,
|
||||
ExpectedContent: []string{
|
||||
`"execTime":`,
|
||||
`"affectedRows":0`,
|
||||
`"columns":[{"name":"id","type":"","nullable":true}]`,
|
||||
`"rows":[["aaa`,
|
||||
},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
},
|
||||
{
|
||||
Name: "single write query",
|
||||
Method: http.MethodPost,
|
||||
URL: "/api/sql",
|
||||
Body: strings.NewReader(`{"query":"create table test_sql_table(id int primary key)"}`),
|
||||
Headers: map[string]string{
|
||||
// superusers, test@example.com
|
||||
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
|
||||
},
|
||||
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
|
||||
if !app.HasTable("test_sql_table") {
|
||||
t.Fatalf("Missing expected new %q table", "test_sql_table")
|
||||
}
|
||||
},
|
||||
ExpectedStatus: 200,
|
||||
ExpectedContent: []string{
|
||||
`"execTime":`,
|
||||
`"affectedRows":0`,
|
||||
`"columns":[]`,
|
||||
`"rows":[]`,
|
||||
},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
},
|
||||
{
|
||||
Name: "multiple write queries",
|
||||
Method: http.MethodPost,
|
||||
URL: "/api/sql",
|
||||
Body: strings.NewReader(`{"query":"create table test_sql_table(id int primary key);insert into test_sql_table(id)VALUES(1)"}`),
|
||||
Headers: map[string]string{
|
||||
// superusers, test@example.com
|
||||
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
|
||||
},
|
||||
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
|
||||
var total int
|
||||
err := app.DB().NewQuery("select count(*) from test_sql_table").Row(&total)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if total != 1 {
|
||||
t.Fatalf("Expected exactly 1 row, found: %d", total)
|
||||
}
|
||||
},
|
||||
ExpectedStatus: 200,
|
||||
ExpectedContent: []string{
|
||||
`"execTime":`,
|
||||
`"affectedRows":1`,
|
||||
`"columns":[]`,
|
||||
`"rows":[]`,
|
||||
},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
},
|
||||
{
|
||||
Name: "multiple write queries (transaction rollback)",
|
||||
Method: http.MethodPost,
|
||||
URL: "/api/sql",
|
||||
Body: strings.NewReader(`{"query":"create table test_sql_table(id int primary key);insert into test_sql_table(id)VALUES(1);invalid"}`),
|
||||
Headers: map[string]string{
|
||||
// superusers, test@example.com
|
||||
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
|
||||
},
|
||||
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
|
||||
if app.HasTable("test_sql_table") {
|
||||
t.Fatalf("Expected table %q to not be created", "test_sql_table")
|
||||
}
|
||||
},
|
||||
ExpectedStatus: 400,
|
||||
ExpectedContent: []string{
|
||||
`"data":{}`,
|
||||
`Raw error:`,
|
||||
`SQL logic error`,
|
||||
},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
},
|
||||
{
|
||||
Name: "multiple read queries",
|
||||
Method: http.MethodPost,
|
||||
URL: "/api/sql",
|
||||
Body: strings.NewReader(`{"query":"select 1;select 2"}`),
|
||||
Headers: map[string]string{
|
||||
// superusers, test@example.com
|
||||
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
|
||||
},
|
||||
ExpectedStatus: 200,
|
||||
ExpectedContent: []string{
|
||||
`"execTime":`,
|
||||
`"affectedRows":0`,
|
||||
// only the result of the last query should be returned
|
||||
`"columns":[{"name":"2","type":"","nullable":true}]`,
|
||||
`"rows":[["2"]]`,
|
||||
},
|
||||
ExpectedEvents: map[string]int{"*": 0},
|
||||
},
|
||||
}
|
||||
|
||||
for _, scenario := range scenarios {
|
||||
scenario.Test(t)
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -4,8 +4,8 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/pocketbase/pocketbase/apis"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/apis"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
|
||||
+39
-3
@@ -5,9 +5,9 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/go-ozzo/ozzo-validation/v4/is"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/security"
|
||||
"github.com/pocketbase/ozzo-validation/v4/is"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tools/security"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
@@ -24,6 +24,7 @@ func NewSuperuserCommand(app core.App) *cobra.Command {
|
||||
command.AddCommand(superuserUpdateCommand(app))
|
||||
command.AddCommand(superuserDeleteCommand(app))
|
||||
command.AddCommand(superuserOTPCommand(app))
|
||||
command.AddCommand(superuserIPsCommand(app))
|
||||
|
||||
return command
|
||||
}
|
||||
@@ -209,3 +210,38 @@ func superuserOTPCommand(app core.App) *cobra.Command {
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
func superuserIPsCommand(app core.App) *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "ips",
|
||||
Example: "superuser ips 127.0.0.1 10.0.0.0/24",
|
||||
Short: "Updates the superuser IPs whitelist setting (the IPs/subnets arguments must be space separated; leave empty to clear the whitelist restriction)",
|
||||
SilenceUsage: true,
|
||||
RunE: func(command *cobra.Command, args []string) error {
|
||||
settings := app.Settings()
|
||||
settings.SuperuserIPs = args
|
||||
|
||||
if err := app.Save(settings); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(args) == 0 {
|
||||
color.Green("Successfully cleared SuperuserIPs setting!")
|
||||
} else {
|
||||
color.New(color.BgGreen, color.FgBlack).Println("Successfully updated SuperuserIPs setting:")
|
||||
superuserIPs := app.Settings().SuperuserIPs
|
||||
for i, ip := range superuserIPs {
|
||||
if i == len(superuserIPs)-1 {
|
||||
color.Green("└─ %s", ip)
|
||||
} else {
|
||||
color.Green("├─ %s", ip)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
+64
-3
@@ -1,11 +1,12 @@
|
||||
package cmd_test
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/cmd"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/cmd"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
)
|
||||
|
||||
func TestSuperuserUpsertCommand(t *testing.T) {
|
||||
@@ -401,3 +402,63 @@ func TestSuperuserOTPCommand(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuperuserIPsCommand(t *testing.T) {
|
||||
app, _ := tests.NewTestApp()
|
||||
defer app.Cleanup()
|
||||
|
||||
scenarios := []struct {
|
||||
name string
|
||||
ips []string
|
||||
expectError bool
|
||||
}{
|
||||
{
|
||||
"no ips",
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"invalid ips",
|
||||
[]string{"127.0.0.1", "invalid"},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"valid ips",
|
||||
[]string{"127.0.0.1", "::1", "127.0.0.1/24"},
|
||||
false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.name, func(t *testing.T) {
|
||||
args := []string{"ips"}
|
||||
args = append(args, s.ips...)
|
||||
|
||||
command := cmd.NewSuperuserCommand(app)
|
||||
command.SetArgs(args)
|
||||
|
||||
err := command.Execute()
|
||||
|
||||
hasErr := err != nil
|
||||
if s.expectError != hasErr {
|
||||
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
|
||||
}
|
||||
|
||||
if hasErr {
|
||||
return
|
||||
}
|
||||
|
||||
settingIPs := app.Settings().SuperuserIPs
|
||||
|
||||
if len(settingIPs) != len(s.ips) {
|
||||
t.Fatalf("Expected %d ips, got %d (%v)", len(s.ips), len(settingIPs), settingIPs)
|
||||
}
|
||||
|
||||
for _, ip := range settingIPs {
|
||||
if !slices.Contains(s.ips, ip) {
|
||||
t.Fatalf("Missing expected ip %q (%v)", ip, settingIPs)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+6
-6
@@ -9,12 +9,12 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/tools/cron"
|
||||
"github.com/pocketbase/pocketbase/tools/filesystem"
|
||||
"github.com/pocketbase/pocketbase/tools/hook"
|
||||
"github.com/pocketbase/pocketbase/tools/mailer"
|
||||
"github.com/pocketbase/pocketbase/tools/store"
|
||||
"github.com/pocketbase/pocketbase/tools/subscriptions"
|
||||
"github.com/tabshift-gh/pocketbase/tools/cron"
|
||||
"github.com/tabshift-gh/pocketbase/tools/filesystem"
|
||||
"github.com/tabshift-gh/pocketbase/tools/hook"
|
||||
"github.com/tabshift-gh/pocketbase/tools/mailer"
|
||||
"github.com/tabshift-gh/pocketbase/tools/store"
|
||||
"github.com/tabshift-gh/pocketbase/tools/subscriptions"
|
||||
)
|
||||
|
||||
// App defines the main PocketBase app interface.
|
||||
|
||||
@@ -5,10 +5,10 @@ import (
|
||||
"errors"
|
||||
"slices"
|
||||
|
||||
validation "github.com/go-ozzo/ozzo-validation/v4"
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/tools/hook"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
validation "github.com/pocketbase/ozzo-validation/v4"
|
||||
"github.com/tabshift-gh/pocketbase/tools/hook"
|
||||
"github.com/tabshift-gh/pocketbase/tools/types"
|
||||
)
|
||||
|
||||
const CollectionNameAuthOrigins = "_authOrigins"
|
||||
|
||||
@@ -5,9 +5,9 @@ import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/tools/types"
|
||||
)
|
||||
|
||||
func TestNewAuthOrigin(t *testing.T) {
|
||||
|
||||
@@ -5,8 +5,8 @@ import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
)
|
||||
|
||||
func TestFindAllAuthOriginsByRecord(t *testing.T) {
|
||||
|
||||
+16
-14
@@ -16,15 +16,15 @@ import (
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/tools/cron"
|
||||
"github.com/pocketbase/pocketbase/tools/filesystem"
|
||||
"github.com/pocketbase/pocketbase/tools/hook"
|
||||
"github.com/pocketbase/pocketbase/tools/logger"
|
||||
"github.com/pocketbase/pocketbase/tools/mailer"
|
||||
"github.com/pocketbase/pocketbase/tools/routine"
|
||||
"github.com/pocketbase/pocketbase/tools/store"
|
||||
"github.com/pocketbase/pocketbase/tools/subscriptions"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
"github.com/tabshift-gh/pocketbase/tools/cron"
|
||||
"github.com/tabshift-gh/pocketbase/tools/filesystem"
|
||||
"github.com/tabshift-gh/pocketbase/tools/hook"
|
||||
"github.com/tabshift-gh/pocketbase/tools/logger"
|
||||
"github.com/tabshift-gh/pocketbase/tools/mailer"
|
||||
"github.com/tabshift-gh/pocketbase/tools/routine"
|
||||
"github.com/tabshift-gh/pocketbase/tools/store"
|
||||
"github.com/tabshift-gh/pocketbase/tools/subscriptions"
|
||||
"github.com/tabshift-gh/pocketbase/tools/types"
|
||||
"github.com/spf13/cast"
|
||||
"golang.org/x/sync/semaphore"
|
||||
)
|
||||
@@ -38,8 +38,9 @@ const (
|
||||
|
||||
LocalStorageDirName string = "storage"
|
||||
LocalBackupsDirName string = "backups"
|
||||
LocalTempDirName string = ".pb_temp_to_delete" // temp pb_data sub directory that will be deleted on each app.Bootstrap()
|
||||
LocalAutocertCacheDirName string = ".autocert_cache"
|
||||
LocalNotifyDirName string = ".notify" // optional watched directory that is used as a cross-platform workaround for synchronizing various runtime states between multiple PocketBase instances pointing to the same pb_data
|
||||
LocalTempDirName string = ".pb_temp_to_delete" // temp pb_data sub directory that will be deleted on each app.Bootstrap()
|
||||
|
||||
// @todo consider removing after backups refactoring
|
||||
lostFoundDirName string = "lost+found"
|
||||
@@ -1233,7 +1234,7 @@ func normalizeSQLLog(sql string) string {
|
||||
|
||||
func (app *BaseApp) initAuxDB() error {
|
||||
// note: renamed to "auxiliary" because "aux" is a reserved Windows filename
|
||||
// (see https://github.com/pocketbase/pocketbase/issues/5607)
|
||||
// (see https://github.com/tabshift-gh/pocketbase/issues/5607)
|
||||
dbPath := filepath.Join(app.DataDir(), "auxiliary.db")
|
||||
|
||||
concurrentDB, err := app.config.DBConnect(dbPath)
|
||||
@@ -1314,7 +1315,7 @@ func (app *BaseApp) registerBaseHooks() {
|
||||
Func: func(e *ModelEvent) error {
|
||||
if m, ok := e.Model.(FilesManager); ok && m.BaseFilesPath() != "" && supportFiles(e.Model) {
|
||||
// ensure that there is a trailing slash so that the list iterator could start walking from the prefix dir
|
||||
// (https://github.com/pocketbase/pocketbase/discussions/5246#discussioncomment-10128955)
|
||||
// (https://github.com/tabshift-gh/pocketbase/discussions/5246#discussioncomment-10128955)
|
||||
prefix := strings.TrimRight(m.BaseFilesPath(), "/") + "/"
|
||||
|
||||
// note: for now assume no context cancellation
|
||||
@@ -1382,6 +1383,7 @@ func (app *BaseApp) registerBaseHooks() {
|
||||
app.registerMFAHooks()
|
||||
app.registerOTPHooks()
|
||||
app.registerAuthOriginHooks()
|
||||
app.registerNotifyWatcherHooks()
|
||||
}
|
||||
|
||||
// getLoggerMinLevel returns the logger min level based on the
|
||||
@@ -1456,7 +1458,7 @@ func (app *BaseApp) initLogger() error {
|
||||
},
|
||||
})
|
||||
|
||||
go func() {
|
||||
routine.FireAndForget(func() {
|
||||
ctx := context.Background()
|
||||
|
||||
for {
|
||||
@@ -1467,7 +1469,7 @@ func (app *BaseApp) initLogger() error {
|
||||
handler.WriteAll(ctx)
|
||||
}
|
||||
}
|
||||
}()
|
||||
})
|
||||
|
||||
app.logger = slog.New(handler)
|
||||
|
||||
|
||||
+26
-7
@@ -12,11 +12,11 @@ import (
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/tools/archive"
|
||||
"github.com/pocketbase/pocketbase/tools/filesystem"
|
||||
"github.com/pocketbase/pocketbase/tools/inflector"
|
||||
"github.com/pocketbase/pocketbase/tools/osutils"
|
||||
"github.com/pocketbase/pocketbase/tools/security"
|
||||
"github.com/tabshift-gh/pocketbase/tools/archive"
|
||||
"github.com/tabshift-gh/pocketbase/tools/filesystem"
|
||||
"github.com/tabshift-gh/pocketbase/tools/inflector"
|
||||
"github.com/tabshift-gh/pocketbase/tools/osutils"
|
||||
"github.com/tabshift-gh/pocketbase/tools/security"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -54,7 +54,13 @@ func (app *BaseApp) CreateBackup(ctx context.Context, name string) error {
|
||||
event.Context = ctx
|
||||
event.Name = name
|
||||
// default root dir entries to exclude from the backup generation
|
||||
event.Exclude = []string{LocalBackupsDirName, LocalTempDirName, LocalAutocertCacheDirName, lostFoundDirName}
|
||||
event.Exclude = []string{
|
||||
LocalBackupsDirName,
|
||||
LocalTempDirName,
|
||||
LocalNotifyDirName,
|
||||
LocalAutocertCacheDirName,
|
||||
lostFoundDirName,
|
||||
}
|
||||
|
||||
return app.OnBackupCreate().Trigger(event, func(e *BackupEvent) error {
|
||||
// generate a default name if missing
|
||||
@@ -145,7 +151,7 @@ func (app *BaseApp) CreateBackup(ctx context.Context, name string) error {
|
||||
//
|
||||
// Note that if your pb_data has custom network mounts as subdirectories, then
|
||||
// it is possible the restore to fail during the `os.Rename` operations
|
||||
// (see https://github.com/pocketbase/pocketbase/issues/4647).
|
||||
// (see https://github.com/tabshift-gh/pocketbase/issues/4647).
|
||||
func (app *BaseApp) RestoreBackup(ctx context.Context, name string) error {
|
||||
if app.Store().Has(StoreKeyActiveBackup) {
|
||||
return errors.New("try again later - another backup/restore operation has already been started")
|
||||
@@ -316,6 +322,19 @@ func (app *BaseApp) registerAutobackupHooks() {
|
||||
slog.String("name", name),
|
||||
slog.String("error", err.Error()),
|
||||
)
|
||||
|
||||
alertError := sendSystemAlertToAllSuperusers(
|
||||
app,
|
||||
"Autobackup failure",
|
||||
"Failed to create/upload automated backup. Raw error:\n"+err.Error(),
|
||||
)
|
||||
if alertError != nil {
|
||||
app.Logger().Warn(
|
||||
"[Backup cron] Failed to send backup error alerts",
|
||||
slog.String("name", name),
|
||||
slog.String("error", alertError.Error()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
maxKeep := app.Settings().Backups.CronMaxKeep
|
||||
|
||||
@@ -9,10 +9,10 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/pocketbase/pocketbase/tools/archive"
|
||||
"github.com/pocketbase/pocketbase/tools/list"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/tools/archive"
|
||||
"github.com/tabshift-gh/pocketbase/tools/list"
|
||||
)
|
||||
|
||||
func TestCreateBackup(t *testing.T) {
|
||||
|
||||
+4
-4
@@ -12,10 +12,10 @@ import (
|
||||
_ "unsafe"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/pocketbase/pocketbase/tools/logger"
|
||||
"github.com/pocketbase/pocketbase/tools/mailer"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/tools/logger"
|
||||
"github.com/tabshift-gh/pocketbase/tools/mailer"
|
||||
)
|
||||
|
||||
func TestNewBaseApp(t *testing.T) {
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"fmt"
|
||||
"slices"
|
||||
|
||||
validation "github.com/go-ozzo/ozzo-validation/v4"
|
||||
validation "github.com/pocketbase/ozzo-validation/v4"
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
|
||||
|
||||
@@ -6,8 +6,8 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
)
|
||||
|
||||
func TestImportCollections(t *testing.T) {
|
||||
|
||||
@@ -7,10 +7,10 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/tools/dbutils"
|
||||
"github.com/pocketbase/pocketbase/tools/hook"
|
||||
"github.com/pocketbase/pocketbase/tools/security"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
"github.com/tabshift-gh/pocketbase/tools/dbutils"
|
||||
"github.com/tabshift-gh/pocketbase/tools/hook"
|
||||
"github.com/tabshift-gh/pocketbase/tools/security"
|
||||
"github.com/tabshift-gh/pocketbase/tools/types"
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
|
||||
@@ -348,6 +348,7 @@ func (app *BaseApp) registerCollectionHooks() {
|
||||
}
|
||||
|
||||
// @todo experiment eventually replacing the rules *string with a struct?
|
||||
// @todo consider changing the Indexes field to a "getter" for the sqlite_master table?
|
||||
type baseCollection struct {
|
||||
BaseModel
|
||||
|
||||
@@ -820,6 +821,25 @@ func onCollectionSave(e *CollectionEvent) error {
|
||||
|
||||
e.Collection.updateGeneratedIdIfExists(e.App)
|
||||
|
||||
// normalize indexes table name
|
||||
for i, raw := range e.Collection.Indexes {
|
||||
parsed := dbutils.ParseIndex(raw)
|
||||
|
||||
// no need to normalize
|
||||
if parsed.TableName == e.Collection.Name {
|
||||
continue
|
||||
}
|
||||
|
||||
parsed.TableName = e.Collection.Name
|
||||
|
||||
normalized := parsed.Build()
|
||||
if normalized == "" {
|
||||
continue // leave to the model validator to decide whether to return an error
|
||||
}
|
||||
|
||||
e.Collection.Indexes[i] = normalized
|
||||
}
|
||||
|
||||
return e.Next()
|
||||
}
|
||||
|
||||
@@ -905,8 +925,14 @@ func onCollectionSaveExecute(e *CollectionEvent) error {
|
||||
}
|
||||
|
||||
// trigger an update for all views with changed fields as a result of the current collection save
|
||||
// (ignoring view errors to allow users to update the query from the UI)
|
||||
resaveViewsWithChangedFields(e.App, e.Collection.Id)
|
||||
// (only log the error to allow users to adjust the problematic view queries from the UI)
|
||||
depViewsErr := resaveViewsWithChangedFields(e.App, e.Collection.Id)
|
||||
if depViewsErr != nil {
|
||||
e.App.Logger().Warn(
|
||||
"Dependent view collection(s) may need to be updated after "+e.Collection.Name+" collection change",
|
||||
"error", depViewsErr,
|
||||
)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -5,12 +5,12 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
validation "github.com/go-ozzo/ozzo-validation/v4"
|
||||
"github.com/go-ozzo/ozzo-validation/v4/is"
|
||||
"github.com/pocketbase/pocketbase/tools/auth"
|
||||
"github.com/pocketbase/pocketbase/tools/list"
|
||||
"github.com/pocketbase/pocketbase/tools/security"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
validation "github.com/pocketbase/ozzo-validation/v4"
|
||||
"github.com/pocketbase/ozzo-validation/v4/is"
|
||||
"github.com/tabshift-gh/pocketbase/tools/auth"
|
||||
"github.com/tabshift-gh/pocketbase/tools/list"
|
||||
"github.com/tabshift-gh/pocketbase/tools/security"
|
||||
"github.com/tabshift-gh/pocketbase/tools/types"
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
|
||||
@@ -70,7 +70,7 @@ func (m *Collection) setDefaultAuthOptions() {
|
||||
},
|
||||
AuthToken: TokenConfig{
|
||||
Secret: security.RandomString(50),
|
||||
Duration: 604800, // 7 days
|
||||
Duration: 432000, // 5days
|
||||
},
|
||||
PasswordResetToken: TokenConfig{
|
||||
Secret: security.RandomString(50),
|
||||
@@ -82,7 +82,7 @@ func (m *Collection) setDefaultAuthOptions() {
|
||||
},
|
||||
VerificationToken: TokenConfig{
|
||||
Secret: security.RandomString(50),
|
||||
Duration: 259200, // 3days
|
||||
Duration: 86400, // 1day
|
||||
},
|
||||
FileToken: TokenConfig{
|
||||
Secret: security.RandomString(50),
|
||||
@@ -461,7 +461,7 @@ type OAuth2ProviderConfig struct {
|
||||
//
|
||||
// This usually shouldn't be needed but some OAuth2 vendors, like the LinkedIn OIDC,
|
||||
// may require manual adjustment due to returning error if extra parameters are added to the request
|
||||
// (https://github.com/pocketbase/pocketbase/discussions/3799#discussioncomment-7640312)
|
||||
// (https://github.com/tabshift-gh/pocketbase/discussions/3799#discussioncomment-7640312)
|
||||
PKCE *bool `form:"pkce" json:"pkce"`
|
||||
|
||||
Name string `form:"name" json:"name"`
|
||||
|
||||
@@ -8,10 +8,10 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/pocketbase/pocketbase/tools/auth"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
"github.com/tabshift-gh/pocketbase/core"
|
||||
"github.com/tabshift-gh/pocketbase/tests"
|
||||
"github.com/tabshift-gh/pocketbase/tools/auth"
|
||||
"github.com/tabshift-gh/pocketbase/tools/types"
|
||||
)
|
||||
|
||||
func TestCollectionAuthOptionsValidate(t *testing.T) {
|
||||
|
||||
@@ -18,6 +18,7 @@ var defaultVerificationTemplate = EmailTemplate{
|
||||
<p>
|
||||
<a class="btn" href="` + EmailPlaceholderAppURL + "/_/#/auth/confirm-verification/" + EmailPlaceholderToken + `" target="_blank" rel="noopener">Verify</a>
|
||||
</p>
|
||||
<p><i>If you didn't recently register, please ignore this email.</i></p>
|
||||
<p>
|
||||
Thanks,<br/>
|
||||
` + EmailPlaceholderAppName + ` team
|
||||
@@ -31,7 +32,7 @@ var defaultResetPasswordTemplate = EmailTemplate{
|
||||
<p>
|
||||
<a class="btn" href="` + EmailPlaceholderAppURL + "/_/#/auth/confirm-password-reset/" + EmailPlaceholderToken + `" target="_blank" rel="noopener">Reset password</a>
|
||||
</p>
|
||||
<p><i>If you didn't ask to reset your password, you can ignore this email.</i></p>
|
||||
<p><i>If you didn't ask to reset your password, please ignore this email.</i></p>
|
||||
<p>
|
||||
Thanks,<br/>
|
||||
` + EmailPlaceholderAppName + ` team
|
||||
@@ -45,7 +46,7 @@ var defaultConfirmEmailChangeTemplate = EmailTemplate{
|
||||
<p>
|
||||
<a class="btn" href="` + EmailPlaceholderAppURL + "/_/#/auth/confirm-email-change/" + EmailPlaceholderToken + `" target="_blank" rel="noopener">Confirm new email</a>
|
||||
</p>
|
||||
<p><i>If you didn't ask to change your email address, you can ignore this email.</i></p>
|
||||
<p><i>If you didn't ask to change your email address, please ignore this email.</i></p>
|
||||
<p>
|
||||
Thanks,<br/>
|
||||
` + EmailPlaceholderAppName + ` team
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user