Compare commits

...
506 Commits
Author SHA1 Message Date
Gani Georgiev 8213ccffb4 renamed variable to avoid confusion 2026-09-02 15:59:58 +03:00
Gani Georgiev e16a9f8b21 bumped goja and regenerated jsvm types 2026-09-02 15:44:19 +03:00
Gani Georgiev 0206f6135c bumped app version 2026-09-02 15:39:09 +03:00
Gani Georgiev e417a26a05 updated backport changelog 2026-09-02 12:41:04 +03:00
Gani Georgiev ac4c30ccbc updated json error test 2026-09-02 12:40:29 +03:00
Gani Georgiev fed5ab9a13 fixed linter warnings 2026-09-02 12:25:01 +03:00
Gani Georgiev 6d9ca9bf9d bumped min go github version to 1.27.1 2026-09-02 12:18:12 +03:00
Gani Georgiev 56f1d1dfdd return an error on invalid fallback param serialization 2026-09-02 12:15:34 +03:00
Gani Georgiev 1b3edbbf5c added invalid index name test 2026-09-02 10:57:00 +03:00
Gani Georgiev 522f9e0ab0 fixed index parsing error when no index name is provided 2026-09-02 10:48:24 +03:00
Gani Georgiev 3c9427667d autocomplete by the word up to the the caret position 2026-09-02 09:37:27 +03:00
Gani Georgiev fd5b9e5f75 clear autocomplete dropdown if empty 2026-09-02 08:10:49 +03:00
Gani Georgiev d0b441bc24 don't show autocomplete if the only suggestion is exact match 2026-09-02 08:05:30 +03:00
Gani Georgiev 229240b374 updated changelog and bumped dev app version 2026-09-02 06:45:06 +03:00
Gani Georgiev f694893d31 bumped highlight limit and slightly debounce autocomplete suggestions 2026-09-02 06:43:11 +03:00
Gani Georgiev 8cb486f24a optimized filter params replacement to use strings.Replacer for a single pass 2026-08-28 12:28:16 +03:00
Gani Georgiev bc8ffed4e7 [#7815] added checks for missing providers prop 2026-08-24 18:00:11 +03:00
Gani Georgiev da18302785 bumped app version 2026-08-24 17:27:07 +03:00
Gani Georgiev b402f11a79 enabled invalid utf8 character replacement by default for the custom json types 2026-08-24 17:26:36 +03:00
Gani Georgiev 9f4f4d4e73 fixed typos 2026-08-24 17:26:01 +03:00
Gani Georgiev d763d3dff1 [#7815] fixed oauth2 providers config merge 2026-08-24 17:07:51 +03:00
Gani Georgiev 04ed202c78 removed unnecessery empty array normalizations because encoding/json/v2 does it by default 2026-08-24 16:46:59 +03:00
Gani Georgiev 756b326bfa allow invalid utf8 characters when marshalizing json responses 2026-08-24 14:13:53 +03:00
Gani Georgiev 50f5f83ace added closed checks as an extra precaution 2026-08-23 00:19:33 +03:00
Gani Georgiev 70d585759d wrap zip close with mutex 2026-08-23 00:05:47 +03:00
Gani Georgiev 9e15b464ba fixed err variable name 2026-08-22 23:43:23 +03:00
Gani Georgiev 129d46f4c8 fixed changelog typo 2026-08-22 23:21:25 +03:00
Gani Georgiev eae29c83a8 updated linter and bumped app version 2026-08-22 23:11:51 +03:00
Gani Georgiev c532fd19b6 wrapped backup zip copy operations in a mutex since the file hook can be triggered by different goroutine 2026-08-22 20:48:54 +03:00
Gani Georgiev eade68d4a3 check for isdir error before logging 2026-08-22 19:27:03 +03:00
Gani Georgiev 18cb3dc62f ugnore dirs to avoid unnecessery logs 2026-08-22 19:18:20 +03:00
Gani Georgiev a293e1301d use the concurrent db pool for the backup db copy 2026-08-22 17:25:37 +03:00
Gani Georgiev 7f4b532f06 updated backport changelog 2026-08-22 16:38:22 +03:00
Gani Georgiev 5e5ba383e8 comment fieldsWithExcerpt to make use of the faster streaming json path 2026-08-22 16:32:11 +03:00
Gani Georgiev b648b951b0 fix some of the flaky tests 2026-08-22 11:33:18 +03:00
Gani Georgiev f544fa0c81 updated tests 2026-08-22 10:10:16 +03:00
Gani Georgiev 80608e8687 updated jstypes 2026-08-21 23:03:19 +03:00
Gani Georgiev 654af12d17 unexport the filesystem hooks for now to avoid introducing breaking changes 2026-08-21 22:58:14 +03:00
Gani Georgiev 0e9dcfe1ab added experimental backup optimizations 2026-08-21 18:50:16 +03:00
Gani Georgiev 25dc8a8eea added Store.Keys() 2026-08-21 14:45:48 +03:00
Gani Georgiev bf1f164014 added Record.GetInt64(field) helper 2026-08-19 21:43:04 +03:00
Gani Georgiev 50a7700450 bumped go github action version to 1.27, updated modernc.org/sqlite and enabled _defensive=1 2026-08-19 21:25:29 +03:00
Gani Georgiev 252358e036 use app.pb.logs.truncate() 2026-08-19 18:12:35 +03:00
Gani Georgiev c2cbd9707f use fixed message limit seperate from the log data 2026-08-19 10:51:06 +03:00
Gani Georgiev e71be7194a added logs truncate endpoint 2026-08-19 10:04:35 +03:00
Gani Georgiev 1a5f29818c split changelogs 2026-08-18 22:56:09 +03:00
Gani Georgiev 25081f14eb make raw json scanning determinisctic and added setting option to limit log data size 2026-08-18 22:46:51 +03:00
Gani Georgiev f5695a7308 bumped app version 2026-08-18 18:34:09 +03:00
Gani Georgiev bad7cc00a1 updated go version in go.mod 2026-08-18 18:24:54 +03:00
Gani Georgiev 14fc20a851 bumped go github action to 1.27rc3 2026-08-18 18:21:29 +03:00
Gani Georgiev 97dd775455 (experimental) upgraded to encoding/json/v2 2026-08-18 18:16:22 +03:00
Gani Georgiev 4d4275c9aa updated custom select class position 2026-08-16 20:45:23 +03:00
Gani Georgiev 1247b24236 synced with master 2026-08-14 10:12:06 +03:00
Gani Georgiev 5d217ddb50 updated backport changelog 2026-08-14 07:16:55 +03:00
Gani Georgiev e0169684c4 bumped golang.org/x/ deps 2026-08-14 07:01:03 +03:00
Gani Georgiev f7229c502f bumped app version and min go github action version 2026-08-14 06:55:28 +03:00
Gani Georgiev 82368a6152 use pb.filter in the search normalization 2026-08-13 14:58:06 +03:00
Gani Georgiev d744647929 updated js-sdk 2026-08-13 14:40:33 +03:00
Gani Georgiev c86fa8890d Merge branch 'master' into develop 2026-08-12 13:02:33 +03:00
Gani Georgiev 3668e1c431 allow new duplicated collection to edit the collection of relation fields 2026-08-12 12:59:52 +03:00
Gani Georgiev a4f1fa33d1 added Cross-Origin-Opener-Policy:same-origin to the default security headers 2026-08-11 18:42:26 +03:00
Gani Georgiev 2262bb4cae merged with master 2026-08-10 08:59:16 +03:00
Gani Georgiev 6212276c82 minor ui fixes and shablon update 2026-08-10 08:44:29 +03:00
Gani Georgiev 9f1a4bcfa5 minor ui base component fixes and shablon update 2026-08-10 08:15:14 +03:00
Gani Georgiev 32fa2ddf77 added filesystem.NewWriter helper 2026-08-03 20:04:54 +03:00
Gani Georgiev dc7482ea67 [#7785] fixed realtime API preview examples 2026-08-03 16:05:58 +03:00
Gani Georgiev b259534df7 added quotes for the default Content-Disposition serving filename in case custom name with special characters is provided 2026-08-02 20:18:02 +03:00
Gani Georgiev 4c6c166603 order new files at the end 2026-08-02 15:45:31 +03:00
Gani Georgiev f9795da8c7 added hasArchiveExtension util 2026-08-02 14:20:31 +03:00
Gani Georgiev 200c19b26f added non-zero exit status support for returned command errors 2026-08-01 15:05:40 +03:00
Gani Georgiev fd25a8ae32 added request verification sample to the curl auth create API preview example for consistency with the SDKs 2026-07-30 17:43:54 +03:00
Gani Georgiev 4dc4387638 updated optional send verification request example 2026-07-30 17:35:23 +03:00
Gani Georgiev 4076537a2c [#7782] fixed API preview examples 2026-07-30 17:20:23 +03:00
Gani Georgiev 0a74d2f25d updated ui/dist 2026-07-29 22:34:20 +03:00
Gani Georgiev 7789297065 updated modernc.org/sqlite to 1.55.0 2026-07-29 21:59:56 +03:00
Gani Georgiev 17628e554c delay the first chart init at the end of the loop to avoid too many animations happening at once 2026-07-29 21:55:39 +03:00
Gani Georgiev 8ec80c9828 bumped app version 2026-07-29 21:20:19 +03:00
Gani Georgiev e83e911b2f [#7781] reverted autorecover panic handling for the cli commands 2026-07-29 18:55:49 +03:00
Gani Georgiev 6b00152847 added logs chart loading placeholder 2026-07-28 10:53:32 +03:00
Gani Georgiev 9f32dfa7ba allow passing noninitialized *filesystem.File values 2026-07-22 23:11:29 +03:00
Gani Georgiev 0cbfc046c7 bumped app version 2026-07-22 20:08:00 +03:00
Gani Georgiev d02016c5fd updated changelogs 2026-07-22 19:44:18 +03:00
Gani Georgiev 9425a5c82f updated goja (should resolve the reported regexp2 dep regression) 2026-07-22 19:41:11 +03:00
Gani Georgiev 244ae1a162 updated fexpr 2026-07-22 19:36:47 +03:00
Gani Georgiev 8af99615c4 [#7771] workaround shift+click in Firefox 2026-07-22 08:00:34 +03:00
Gani Georgiev cc4e857090 updated jsvm types 2026-07-19 16:43:28 +03:00
Gani Georgiev ae2cb3c772 updated backport changelog 2026-07-19 16:26:37 +03:00
Gani Georgiev fe6811f824 bumped app version 2026-07-19 16:20:19 +03:00
Gani Georgiev 77bd87b4d1 updated text and password fields number input settings events 2026-07-19 16:18:23 +03:00
Gani Georgiev 7964a8ce43 [#7759] added shift+click bulk selection 2026-07-18 10:17:38 +03:00
Gani Georgiev 09af56b342 prevent resetting number inputs with leading 0 while still typing 2026-07-17 22:00:08 +03:00
Gani Georgiev 6aa6b2c471 updated ui/dist 2026-07-16 20:11:30 +03:00
Gani Georgiev a51a53db97 updated modernc.org/sqlite to 1.54.0 2026-07-16 18:19:32 +03:00
Gani Georgiev 4ea2513b62 added extra panic-recover handling for CreateThumb 2026-07-16 18:14:07 +03:00
Gani Georgiev b419498d9c properly reset JSVM global app state overwrite so that pooled executors always get a clean state 2026-07-16 17:12:27 +03:00
Gani Georgiev 636b7e28d8 bumped app version 2026-07-16 07:38:52 +03:00
Gani Georgiev 015ed81e05 updated jsvm types 2026-07-16 06:49:42 +03:00
Gani Georgiev 2f802866f9 updated SafeWrap tests 2026-07-16 06:30:18 +03:00
Gani Georgiev bea265cf26 updated backport changelog 2026-07-15 15:01:17 +03:00
Gani Georgiev dcb9cf3d0a run gofmt 2026-07-15 13:14:52 +03:00
Gani Georgiev f1618ee59b fixed unhandled panic and wrapped all internal goroutines 2026-07-15 12:03:07 +03:00
Gani Georgiev 09044ef7a3 updated tooltip text 2026-07-15 11:56:07 +03:00
Gani Georgiev 3c880378c9 fixed arg validation 2026-07-15 11:51:15 +03:00
Gani Georgiev c388ade7f0 [#7761] fixed view collection * validator and added more friendly error messages 2026-07-15 08:00:39 +03:00
Gani Georgiev 7ec875a49e use tagged ozzo-validation 2026-07-13 23:04:20 +03:00
Gani Georgiev 4bc71adc19 use tagged tygoja 2026-07-13 22:34:04 +03:00
Gani Georgiev 4221a1b803 [#7760] fixed missing import collection fields property access 2026-07-13 20:41:10 +03:00
Gani Georgiev 0c7d243d97 swapped github.com/go-ozzo/ozzo-validation with github.com/pocketbase/ozzo-validation 2026-07-13 08:42:59 +03:00
Gani Georgiev 089ca8ae41 updated the security policy with note about the JSVM 2026-07-12 11:39:21 +03:00
Gani Georgiev de3c3f715b updated goja (WeakMap fixes) 2026-07-08 07:14:34 +03:00
Gani Georgiev 2128a95450 updated changelogs and bumped app version 2026-07-08 06:52:34 +03:00
Gani Georgiev 692e0f0789 updated min go github action version to 1.26.5 2026-07-08 06:49:28 +03:00
Gani Georgiev e646b8ebac shortened help texts 2026-07-08 06:48:28 +03:00
Gani Georgiev b5bed248d1 updated jsvm types 2026-07-06 20:57:44 +03:00
Gani Georgiev 1cfc503bcd added conditional default openid scope and helper text to remind users for the required permissions 2026-07-06 20:51:19 +03:00
Gani Georgiev 7327f0cf33 updated ui/dist 2026-07-06 16:28:31 +03:00
Gani Georgiev c220a61ef4 fixed test typo 2026-07-06 16:02:26 +03:00
Gani Georgiev b2ed234d74 added Cc and Bcc headers to the sendmail command 2026-07-06 16:02:14 +03:00
Gani Georgiev 7b3f4d62b1 added extra hardening options to the Microsoft OAuth2 provider allowing devs to specify the preferred safe email extraction method 2026-07-06 15:44:37 +03:00
Gani Georgiev 667a765070 updated ui/dist 2026-06-28 10:35:41 +03:00
Gani Georgiev 61d2ca3e60 force close modals on collection or record deletion 2026-06-28 10:35:21 +03:00
Gani Georgiev 6d724ba6e0 bumped app version 2026-06-28 10:27:57 +03:00
Gani Georgiev 71ea799e45 bumped preload cleanup delay 2026-06-28 10:14:44 +03:00
Gani Georgiev ed076328cb preload tinymce only for collections with editor field 2026-06-27 16:05:28 +03:00
Gani Georgiev 13bc3a12c0 updated goja 2026-06-27 12:25:11 +03:00
Gani Georgiev 3a9a341527 [#7746] readded editor fullscreen option and preloaded the tinymce component 2026-06-27 12:13:42 +03:00
Gani Georgiev 2d4d830203 updated shablon 2026-06-21 21:37:58 +03:00
Gani Georgiev be6671b2eb fix long url field value scroll view 2026-06-20 12:34:25 +03:00
Gani Georgiev 8d30cb57e2 fixed grammar 2026-06-14 19:02:43 +03:00
Gani Georgiev 507ecb264b updated goja 2026-06-14 18:25:21 +03:00
Gani Georgiev 07471c94d1 updated local selected after updating the record value 2026-06-14 18:14:27 +03:00
Gani Georgiev 29b755243c bumped app version 2026-06-14 17:53:24 +03:00
Gani Georgiev c8b0c5884d fixed sortable index count when there is a before element 2026-06-14 15:08:25 +03:00
Gani Georgiev 1fa662bb92 add list reset to the record rid 2026-06-13 16:48:16 +03:00
Gani Georgiev 25d0026686 [#7735] enabled sorting by the first implicit presentable relation field 2026-06-13 16:16:00 +03:00
Gani Georgiev a20ead67f1 ensure that the starting slide styles are always applied 2026-06-13 15:11:53 +03:00
Gani Georgiev 2818208909 [#7734] removed RedirectURL required validator 2026-06-13 14:55:07 +03:00
Gani Georgiev 2e9cc27fc8 hide related tooltip on element removal 2026-06-12 12:31:43 +03:00
Gani Georgiev 01dcb5aaf3 fixed abort check 2026-06-09 08:38:23 +03:00
Gani Georgiev 465cfb5293 bumped app version 2026-06-08 18:54:43 +03:00
Gani Georgiev f58a65e4be apply the save shortcut only for the top open modal 2026-06-08 16:06:45 +03:00
Gani Georgiev aa7be1edd1 don't recreate the maxSelect inputs on each change 2026-06-08 14:26:58 +03:00
Gani Georgiev f868756721 fixed number settings 0 max validator 2026-06-08 12:57:44 +03:00
Gani Georgiev b66a4e32cc replace type text with number 2026-06-08 10:27:28 +03:00
Gani Georgiev 72df31e22d normalized fields setting tooltip texts 2026-06-08 09:57:50 +03:00
Gani Georgiev 77639f94ce normalized field settings argument name and multiple required tooltip 2026-06-08 09:50:49 +03:00
Gani Georgiev bff6b4c3ab [#7731] fixed file field settings variable name 2026-06-08 09:23:33 +03:00
Gani Georgiev aee115a99f fixed typo 2026-06-07 11:14:23 +03:00
Gani Georgiev b81d92dbd2 updated changelog 2026-06-07 11:13:09 +03:00
Gani Georgiev 98a0f5eb05 updated ui/dist 2026-06-07 10:49:42 +03:00
Gani Georgiev 3350ae651d return filepath.SkipDir instead of nil for excluded dir entries 2026-06-07 10:45:48 +03:00
Gani Georgiev 394a46f3a2 updated modernc.org/sqlite to v1.52.0 2026-06-06 19:33:13 +03:00
Gani Georgiev 4624e84b50 added some extra known write query keywords to the slq api and hide the Affected rows in case empty to avoid ambiguities 2026-06-06 19:25:41 +03:00
Gani Georgiev 21dd105d9a [#7726] don't clear date input on invalid value while still typing 2026-06-05 20:28:24 +03:00
Gani Georgiev 8d60b928fc updated shablon to preserve the original order of new elements 2026-06-04 16:21:21 +03:00
Gani Georgiev e7ae0bd716 [#7724] updated Shablon to fix records list sorting 2026-06-04 15:58:42 +03:00
Gani Georgiev 4752ed84c7 update example code 2026-06-04 15:57:41 +03:00
Gani Georgiev 5631d9b1c2 fixed typos 2026-06-03 16:14:28 +03:00
Gani Georgiev b36b8e35af updated ui/dist 2026-06-03 15:17:55 +03:00
Gani Georgiev 9ff3e5a895 bumped min go github action version to 1.26.4 2026-06-03 15:11:07 +03:00
Gani Georgiev e5964e739e updated code comments and fixed checkApiError legacy calls 2026-06-02 14:07:33 +03:00
Gani Georgiev 40d2849aa6 added default panic-recover handling for the cron jobs 2026-05-31 10:34:27 +03:00
Gani Georgiev f3ae7731d4 simplified and fixed flaky test 2026-05-30 15:01:58 +03:00
Gani Georgiev 1c3a912532 [#7721] return the hidden record data fields for superusers realtime subscribers 2026-05-30 14:58:34 +03:00
Gani Georgiev 2b61b2babf allow label word breaking for the responsive layout 2026-05-29 19:36:52 +03:00
Gani Georgiev d4b73af2e9 updated ui/dist 2026-05-29 19:32:02 +03:00
Gani Georgiev b11731222f fixed typo 2026-05-29 19:29:08 +03:00
Gani Georgiev f1873ad26d [#7720] fixed multiple select options wrapping 2026-05-29 19:27:56 +03:00
Gani Georgiev aeb78e51a1 reference the correct announcement 2026-05-28 18:23:05 +03:00
Gani Georgiev 541aa6b1e1 updated ui/dist and changelog 2026-05-28 18:19:11 +03:00
Gani Georgiev a9f259a1c7 updated modernc.org/sqlite to 1.51.0 2026-05-28 18:18:00 +03:00
Gani Georgiev a2d4f12071 fixed grammar 2026-05-28 18:16:38 +03:00
Gani Georgiev 846432f4c8 added the new no-llm security policy 2026-05-28 18:04:04 +03:00
Gani Georgiev 167e23e9ba added extra confirm verification guards 2026-05-27 09:56:16 +03:00
Gani Georgiev ea2ef87d08 updated btn loading animation 2026-05-26 19:20:52 +03:00
Gani Georgiev e067bf1517 fixed bulkbar wrapper clickthrough and normalized exported filename dates 2026-05-26 18:47:05 +03:00
Gani Georgiev 97b85334a9 removed legacy remember me redirect 2026-05-26 18:22:17 +03:00
Gani Georgiev d4026ce60f [#7698] send system email alerts to superusers in case of an error with the automated backups 2026-05-26 16:54:45 +03:00
Gani Georgiev 40c631db32 clarified the note regarding social engineering attacks 2026-05-26 10:32:13 +03:00
Gani Georgiev 095b0aca51 updated migratecmd template tests 2026-05-26 10:00:08 +03:00
Gani Georgiev a7dfbbb8ec updated the security policy of the project 2026-05-26 09:49:30 +03:00
Gani Georgiev b65b7c5c56 updated default email texts for consistency and set slightly smaller default token durations 2026-05-26 09:33:03 +03:00
Gani Georgiev 4ebdfe4a1e updated default email texts for consistency and set a smaller default verification token duration 2026-05-26 09:31:50 +03:00
Gani Georgiev 19db35c48c updated raw sql length limit to 5000 for consistency with the dry-run-view-query 2026-05-25 12:45:37 +03:00
Gani Georgiev 1034dc9842 registered missing oidc2/oidc3 option fields 2026-05-25 07:19:34 +03:00
Gani Georgiev 5bea84b94b updated js-sdk and replaced missing handlers 2026-05-24 16:09:11 +03:00
Gani Georgiev 7984e586a8 minor ui adjustments 2026-05-24 10:52:37 +03:00
Gani Georgiev b022e138d4 minimal sql console API and UI 2026-05-24 09:30:30 +03:00
Gani Georgiev db853850ab allow word breaking in labels 2026-05-23 22:39:30 +03:00
Gani Georgiev 3d3d3b7355 fixed logs bulk selection 2026-05-23 10:52:49 +03:00
Gani Georgiev 3616b9d667 updated backport changelog 2026-05-22 07:20:20 +03:00
Gani Georgiev efd9604aa7 updated jsvm types 2026-05-22 07:14:50 +03:00
Gani Georgiev 1ab6bba61b updated golang.org/x dependencies 2026-05-22 06:24:21 +03:00
Gani Georgiev 9e6b4eeda8 updated reload tooltip and bumped app version 2026-05-21 19:00:58 +03:00
Gani Georgiev ea1a537a60 allow the select empty and placeholder props to be reactive functions 2026-05-20 16:39:59 +03:00
Gani Georgiev 23a989118c updated shablon 2026-05-20 16:27:19 +03:00
Gani Georgiev d0b2551e78 [#7694] don't reset the records list pagination on record update 2026-05-18 19:26:17 +03:00
Gani Georgiev b9b0e5ae80 added extra IP checks for the connected realtime client 2026-05-18 19:13:25 +03:00
Gani Georgiev f7fbc6c2c3 added RealtimeConnectRequestEvent.MaxTimeout field 2026-05-18 11:40:46 +03:00
Gani Georgiev a286d28bf9 fixed changelog typo 2026-05-15 07:34:50 +03:00
Gani Georgiev 5cff808438 updated error message and regenerated jsvm types 2026-05-15 07:23:25 +03:00
Gani Georgiev 45e3ca6ea6 normalized scaffold indexes 2026-05-15 07:06:56 +03:00
Gani Georgiev 9c8557a124 updated changelog 2026-05-15 06:32:58 +03:00
Gani Georgiev 8d7e3abbd6 [#7689] fixed indexes update collection error 2026-05-14 21:32:21 +03:00
Gani Georgiev 9d50e20880 updated api preview examples 2026-05-14 10:02:42 +03:00
Gani Georgiev fbf4f3e5fb updated modernc.org/sqlite 2026-05-14 09:26:13 +03:00
Gani Georgiev 820b9afe98 added error marker for each collection tab and fixed the styles of the raw errors tooltip 2026-05-14 09:15:05 +03:00
Gani Georgiev b061673d9a updated test to trigger the entire save hook chain 2026-05-13 23:11:10 +03:00
Gani Georgiev c9c47dc75c removed duplicated entry from the backport changelog 2026-05-13 22:49:25 +03:00
Gani Georgiev cbb7c061a3 updated backport changelog 2026-05-13 22:48:35 +03:00
Gani Georgiev caad25bb61 fixed grammar 2026-05-13 22:37:28 +03:00
Gani Georgiev 3b98059a8a force unset realtime connections auth state 2026-05-13 22:34:50 +03:00
Gani Georgiev a8c236a54d fixed ui extensions test 2026-05-10 14:41:53 +03:00
Gani Georgiev 81a5672498 updated ui extensions api to allow top-level await calls 2026-05-10 14:36:09 +03:00
Gani Georgiev 1b5ea9a1fa silenced the superuser ips confirmation if there is no change 2026-05-07 22:57:45 +03:00
Gani Georgiev d438c6a96a bumped app version 2026-05-07 19:51:35 +03:00
Gani Georgiev 6828ca1d4e bumped min go github action version to 1.26.3 2026-05-07 19:49:22 +03:00
Gani Georgiev 88193b9396 adjusted noitems alignment 2026-05-07 19:39:33 +03:00
Gani Georgiev 3cedf032ca [#7681] changed settings app url input to type=text 2026-05-06 19:40:44 +03:00
Gani Georgiev 4396369bb9 removed unused css file 2026-05-06 10:30:11 +03:00
Gani Georgiev 4a4f8ad9db use input css vars and updated changelog 2026-05-06 00:56:12 +03:00
Gani Georgiev 5a144e1342 [#6410] added rate limit option to exclude IPs/CIDR subnets 2026-05-05 17:29:25 +03:00
Gani Georgiev 24d72877e9 updated default log level marker color 2026-05-05 14:12:51 +03:00
Gani Georgiev c40f519b7b bump dev version for the demo 2026-05-05 14:02:10 +03:00
Gani Georgiev b026c6844b updated changelog 2026-05-05 14:01:18 +03:00
Gani Georgiev 21a5524fed added superuser ips whitelist 2026-05-05 13:04:06 +03:00
Gani Georgiev fe2d90641c added content-type serving exception tests 2026-05-05 11:40:07 +03:00
Gani Georgiev 8091a756e8 rollback plex-sans since the feedback from the user wasn't ok (inter was still 'fuzzy') 2026-05-04 21:47:57 +03:00
Gani Georgiev 7542cd14e2 [#7677] fixed default ui csp to allow iframe/object previews 2026-05-04 13:39:21 +03:00
Gani Georgiev 7da023f345 [#7467] forced serving conten-type for xlsx, docx and pptx 2026-05-04 13:14:56 +03:00
Gani Georgiev a104de5b9f fixed minor alignment issues after the font replacement 2026-05-04 11:40:40 +03:00
Gani Georgiev 97c5f3fa02 replaced ibm plex sans with inter 2026-05-04 10:50:41 +03:00
Gani Georgiev fccfa20653 added logs list start date guard 2026-05-04 09:49:32 +03:00
Gani Georgiev 29c6dacbfc updated changelog 2026-05-04 09:35:42 +03:00
Gani Georgiev d33927718b removed unnecessery logs filter normalization breaking the pagination 2026-05-04 09:33:47 +03:00
Gani Georgiev d153553d52 added eager alg error check to minimize misuse 2026-05-02 23:50:05 +03:00
Gani Georgiev db88253aac adjusted default button css 2026-05-02 10:05:43 +03:00
Gani Georgiev 0cf34c475b updated changelog 2026-05-02 07:34:50 +03:00
Gani Georgiev 547ee715c0 slightly adjusted the dark text color 2026-05-01 20:55:17 +03:00
Gani Georgiev 4850da6f56 adjusted flaky test 2026-05-01 19:32:00 +03:00
Gani Georgiev 53ac0d29da reordered change email validations to make enumerations slightly harder 2026-05-01 19:31:50 +03:00
Gani Georgiev d90aaedc00 skip duplicated records ids from the IN expand 2026-05-01 19:16:53 +03:00
Gani Georgiev 74defc48b9 fixed editor keydown propagation outside of form 2026-05-01 18:11:06 +03:00
Gani Georgiev 9205b11dc3 bumped app version 2026-05-01 17:51:40 +03:00
Gani Georgiev 8d0881db3f reload trusted proxy info UI after settings save 2026-04-29 11:06:26 +03:00
Gani Georgiev dbcd95eb62 updated the security policy 2026-04-28 12:10:24 +03:00
Gani Georgiev 905256b0c8 added the local time zone name next to the date field label 2026-04-27 22:38:27 +03:00
Gani Georgiev 602f3a4442 added auth collection specific check in the replacer 2026-04-27 22:38:03 +03:00
Gani Georgiev 5c9bcfaf8e [#7670] fixed password fields not being detected as changed 2026-04-27 17:41:19 +03:00
Gani Georgiev 44bf55097a updated changelogs 2026-04-27 09:30:32 +03:00
Gani Georgiev 338d672bee updated ui/dist 2026-04-27 09:04:38 +03:00
Gani Georgiev 5bd9d87bad reorder editor buttons to avoid dropdowns text wrapping 2026-04-27 08:47:14 +03:00
Gani Georgiev 6ba78d5218 updated gitlab userinfo doc reference 2026-04-27 08:03:20 +03:00
Gani Georgiev 260bd59c5b updated jstypes 2026-04-27 07:57:43 +03:00
Gani Georgiev 006566478a added explicit gitlab confirmed_at check 2026-04-27 07:55:51 +03:00
Gani Georgiev 419f335f5b various minor ui fixes 2026-04-27 01:13:08 +03:00
Gani Georgiev 326f150db2 added more tests for internal record hooks 2026-04-26 20:47:47 +03:00
Gani Georgiev 1c86addc4c [#7665] added BaseURL to the ghupdate plugin configuration 2026-04-26 20:47:02 +03:00
Gani Georgiev 494f47efb8 bumped go deps 2026-04-26 16:50:24 +03:00
Gani Georgiev 555a4f1a1e lowered the default mfa duration and reorganized internal record pre/post handling 2026-04-26 16:46:16 +03:00
Gani Georgiev 37b258810a updated gitea displayName 2026-04-26 14:23:23 +03:00
Gani Georgiev ca7cf1162f added App.DeleteAllExternalAuthsByRecord 2026-04-26 11:40:09 +03:00
Gani Georgiev dddb0a029f updated bitbucket,github and gitea oauth2 providers 2026-04-25 17:51:28 +03:00
Gani Georgiev 5d55fc18ee added dummy bcrypt check 2026-04-25 16:16:23 +03:00
Gani Georgiev 449e5af590 adjust dark text color 2026-04-25 11:41:09 +03:00
Gani Georgiev 1e460d3f96 updated changelog and rebuild ui/dist 2026-04-24 22:27:26 +03:00
Gani Georgiev b5030ddfa1 [#7664] fixed codeEditor not firing the change and input events on autocomplete selection 2026-04-24 22:08:58 +03:00
Gani Georgiev fbeb09c40b [#7660] added missing type:button attribute and replaced form tag with div to minimize future regressions 2026-04-24 15:42:47 +03:00
Gani Georgiev 69cdda4bf3 [#7659] fixed SMTP IPv6 format 2026-04-23 21:25:58 +03:00
Gani Georgiev e708f39e1b updated erd styles 2026-04-23 21:18:32 +03:00
Gani Georgiev 52eccb3aac fade non-focused erd tables 2026-04-23 17:43:15 +03:00
Gani Georgiev 1d593476b0 updated view autocomplete keywords 2026-04-23 17:32:07 +03:00
Gani Georgiev 8a04904de1 fixed godoc example typo 2026-04-23 16:57:26 +03:00
Gani Georgiev a3ac674f36 removed title loader to minimize layout jumps 2026-04-23 14:12:59 +03:00
Gani Georgiev ae7041a889 preload the record preview to minimize content jumps 2026-04-23 00:37:05 +03:00
Gani Georgiev 257f03e1fa removed lazy tinymce mount since the relation are now preloaded 2026-04-23 00:01:43 +03:00
Gani Georgiev 3566ba3729 exclude expand from the record draft 2026-04-22 23:15:46 +03:00
Gani Georgiev a6002c4622 optimized record upsert panel loading to minimize layout jumps 2026-04-22 23:02:56 +03:00
Gani Georgiev 2ddf161314 renamed list-group to list-content for consistency with the others 2026-04-22 17:59:11 +03:00
Gani Georgiev b15f358fc9 [#7655] added backups list scroll container 2026-04-22 17:22:22 +03:00
Gani Georgiev 83e44a7cfb added view query sample loading indicator 2026-04-22 16:04:57 +03:00
Gani Georgiev 866b8b8029 added missing name attribute, fixed initial collections page load routing params persistence and removed unnecessery sub label required mark 2026-04-22 15:42:17 +03:00
Gani Georgiev 857214e10d reordered number settings for consistency with the other fields 2026-04-22 14:46:19 +03:00
Gani Georgiev 592b13913f added min-height to the page tables and adjusted light surface colors 2026-04-22 07:00:36 +03:00
Gani Georgiev 84b50c4869 minor color and styles improvements 2026-04-21 17:40:11 +03:00
Gani Georgiev 3c33868ea8 [#7653] updated tinymce options to fix its dialogs position 2026-04-21 14:16:23 +03:00
Gani Georgiev 223ac7a64a enabled text wrapping for the API rule fileds 2026-04-21 11:52:45 +03:00
Gani Georgiev 0cee0662f6 fixed 0 total count on page back/forward navigation 2026-04-21 10:26:37 +03:00
Gani Georgiev bf1745fa13 fixed changelog typo 2026-04-20 17:40:11 +03:00
Gani Georgiev efc095f7d0 updated changelog and ui/dist 2026-04-20 17:26:00 +03:00
Gani Georgiev 14e7286840 updated color vars and hide Safari negative margin horizontal scroll 2026-04-20 16:51:20 +03:00
Gani Georgiev 4ace75b3d5 [#7650] workarounded Safari position-try-fallbacks freeze 2026-04-20 16:49:55 +03:00
Gani Georgiev d23963aaca updated dark complementary colors 2026-04-20 12:25:04 +03:00
Gani Georgiev d35a0d841c [#7649] renamed the stringify util and removed its unnecessery tags stripping 2026-04-20 11:48:44 +03:00
Gani Georgiev 1b18ab9bec [#7648] darken the surface colors a little bit more 2026-04-20 10:32:23 +03:00
Gani Georgiev 93e6ebfe49 [#7648] fixed firefox autoexpandable input and updated dark theme colors 2026-04-19 23:44:04 +03:00
Gani Georgiev c3a53cb183 fallback to 0 2026-04-19 15:36:38 +03:00
Gani Georgiev ba554b8470 [#7646] fixed number field min/max input value normalization 2026-04-19 15:31:33 +03:00
Gani Georgiev 61ce760e0f show collection name in the page title on initial load 2026-04-19 12:29:45 +03:00
Gani Georgiev 7b92b7c857 updated ui/dist 2026-04-19 12:20:37 +03:00
Gani Georgiev 8c127b2849 updated changelog 2026-04-19 11:54:57 +03:00
Gani Georgiev e6b8841421 allow to open collections page in new tab on middle click and minor flickering improvements 2026-04-19 11:53:24 +03:00
Gani Georgiev 862064e061 enable back npm build check 2026-04-19 09:45:41 +03:00
Gani Georgiev 90594cc331 temp disable npm build check 2026-04-19 09:19:52 +03:00
Gani Georgiev 6012ba701d fixed relation and file custom change event trigger 2026-04-19 08:52:40 +03:00
Gani Georgiev 5cc95a2e63 reset responsive table padding and min-height 2026-04-19 08:33:32 +03:00
Gani Georgiev e41f43241b reorder records list watchers and cancel prev count requests 2026-04-19 08:28:03 +03:00
Gani Georgiev 3ad737e606 sync superusers mfa and otp toggles 2026-04-19 01:22:42 +03:00
Gani Georgiev 3b49e8489e added otp superusers help tooltip 2026-04-19 01:19:38 +03:00
Gani Georgiev 07679dd5ba fixed collection getter 2026-04-19 00:57:24 +03:00
Gani Georgiev 3b8bb4cba9 updated changelog 2026-04-19 00:02:25 +03:00
Gani Georgiev e63fdf4dd0 updated changelog and /ui/dist 2026-04-18 23:55:24 +03:00
Gani Georgiev c96415caae responsive adjustments 2026-04-18 22:47:10 +03:00
Gani Georgiev 075e20efae minor screen reader improvements 2026-04-18 22:11:58 +03:00
Gani Georgiev 624c3357be sync forgotten field tooltip 2026-04-18 18:34:18 +03:00
Gani Georgiev 7673798fa3 normalized the names of the exposed jsvm bind funcs 2026-04-18 17:48:41 +03:00
Gani Georgiev d4987a153e updated modernc.org/sqlite to v1.49.1 2026-04-18 17:39:10 +03:00
Gani Georgiev b02d9b3662 updated node action 2026-04-18 17:33:21 +03:00
Gani Georgiev 4c44044c0c merge newui branch 2026-04-18 16:50:39 +03:00
Gani Georgiev 58f605e90c bumped modernc.org/sqlite to 1.48.2 2026-04-09 17:34:00 +03:00
Gani Georgiev 6ae3d47eeb updated changelog 2026-04-09 13:06:34 +03:00
Gani Georgiev cb185ad6bf ratelimit test flakiness adjustments 2026-04-09 10:31:03 +03:00
Gani Georgiev f89858f1ec [#7632] added missing error check in the jsvm watcher 2026-04-09 10:12:58 +03:00
Gani Georgiev 0695ca254d [#7630] added missing file close after seek error 2026-04-09 09:50:36 +03:00
Gani Georgiev e91694154f bumped ui/dist and go action version 2026-04-08 14:27:53 +03:00
Gani Georgiev b251a4cf65 updated backport changelog 2026-04-07 08:35:24 +03:00
Gani Georgiev 01949b059b removed unnecessery struct wrapping 2026-04-05 16:28:11 +03:00
Gani Georgiev 89f3668da2 updated settings update test 2026-04-05 14:15:12 +03:00
Gani Georgiev 7865ca7b95 updated jsvm types 2026-04-05 13:51:57 +03:00
Gani Georgiev d92a98b100 fixed settings smtp password clear persistence 2026-04-05 13:47:06 +03:00
Gani Georgiev e9118fa6b6 removed unnecessery error return 2026-04-02 21:00:16 +03:00
Gani Georgiev e49b64b114 attempt to reduce ratelimit test flakiness 2026-04-02 20:22:16 +03:00
Gani Georgiev 1204362e9c use the raw address in the error message 2026-04-02 20:12:01 +03:00
Gani Georgiev cc535cde3b updated ui/dist 2026-04-02 20:03:56 +03:00
Gani Georgiev cb44d9e716 added extra OAuth2 avatar url download checks 2026-04-02 19:55:05 +03:00
Gani Georgiev 5cb66bd52f updated .static jsvm docs 2026-04-02 08:06:51 +03:00
Gani Georgiev 3a893d15ad avoid explicit fs.FS wrapping 2026-04-02 08:06:11 +03:00
Gani Georgiev 64854ef08d fixed changelog typos 2026-03-30 21:38:11 +03:00
Gani Georgiev 9f3cdf4ad5 use the explicitly mapped username column name for the unique legacy checks 2026-03-30 08:51:11 +03:00
Gani Georgiev 2dbc70d60d assign discord avatar only if exist 2026-03-30 08:15:26 +03:00
Gani GeorgievandHans a2b14bcb93 [#7603] updated the Discord AuthUser.Name field to use global_name
Co-authored-by: Hans <hi@hans0805.me>
2026-03-30 07:42:22 +03:00
Gani Georgiev 864bac6dc4 fixed grammar 2026-03-28 10:22:37 +02:00
Gani Georgiev 78dc12dc29 regenerated jsvm types 2026-03-28 01:14:43 +02:00
Gani Georgiev 4b4c2ec7c3 updated ui/dist 2026-03-28 00:22:41 +02:00
Gani Georgiev d87fa3bd80 bumped go deps 2026-03-28 00:16:34 +02:00
Gani Georgiev 45d353ffdb fixed OAuth2 client secret reset when marshalizing a cached collection model 2026-03-27 23:56:17 +02:00
Gani Georgiev e5390c3d86 added missing error return and fixed comment typo 2026-03-19 08:48:30 +02:00
Gani Georgiev e3d2608d03 updated backport changelog 2026-03-16 19:01:40 +02:00
Gani Georgiev 650a4255cc updated changelog 2026-03-16 18:58:08 +02:00
Gani Georgiev de70af2584 updated npm deps and ui/dist 2026-03-16 18:52:51 +02:00
Gani Georgiev ba7ed78b73 updated modernc.org/sqlite to 1.46.2 (SQLite 3.51.3) 2026-03-16 18:45:54 +02:00
Gani Georgiev cea149cb6e updated jsvm types 2026-03-11 15:02:59 +02:00
Gani Georgiev 70d8d1ee9d replace the custom ratelimiter strategy with a fixed window 2026-03-11 11:25:15 +02:00
Gani Georgiev 29c2e209f4 updated ui/dist 2026-03-09 17:33:04 +02:00
Gani Georgiev ef465957ff fixed comment typo 2026-03-09 17:30:35 +02:00
Gani Georgiev ba8b51af58 [#7575] use memory+file buffer when rereading the request body (fix #7572) 2026-03-09 17:19:09 +02:00
Gani Georgiev 93e3eb3a35 regenerated jsvm types 2026-03-06 09:27:44 +02:00
Gani Georgiev cf77c0e7eb updated v0.22 changelog 2026-03-06 09:23:27 +02:00
Gani Georgiev d4578c3b8c bumped min Go GitHub action version to 1.26.1 2026-03-06 09:17:00 +02:00
Gani Georgiev c2f3fe6a52 fix typo 2026-03-05 10:57:34 +02:00
Gani Georgiev bb18799a0b applied lint typo fixes 2026-03-04 22:31:27 +02:00
Gani Georgiev 4a40c1b897 added todo for the extra rule constraint 2026-03-04 22:14:49 +02:00
Gani Georgiev e9d4b1fe77 limit the debug stack trace of FireAndForget to 2kb 2026-03-01 23:39:30 +02:00
Gani Georgiev 9cefd0128c updated changelog 2026-03-01 00:15:25 +02:00
Gani Georgiev d695e9d180 wrap extra client-side ListRule filter with existence check and replaced the map with a slice to minimize test flakiness 2026-03-01 00:09:05 +02:00
Gani Georgiev faf96896e7 fixed formatting 2026-02-28 23:44:12 +02:00
Gani Georgiev 72364bf4e0 fixed grammar 2026-02-27 09:06:59 +02:00
Gani Georgiev 969d4e2bfb updated ui/dist 2026-02-27 08:50:49 +02:00
Gani Georgiev 430d892e64 fixed grammar 2026-02-27 08:49:51 +02:00
Gani Georgiev fb8af7a8cf bumped npm deps 2026-02-27 08:27:57 +02:00
Gani Georgiev 6ecb412849 updated changelog 2026-02-24 23:02:58 +02:00
Gani Georgiev bc7080337e check the data again after the GetOrSet write lock 2026-02-24 23:02:11 +02:00
Gani Georgiev c157331721 updated the security policy 2026-02-24 22:09:34 +02:00
Gani Georgiev 27ab2d45e8 fixed typo 2026-02-24 15:19:25 +02:00
Gani Georgiev d5d8decf6e [#7543] documented the unmarshal jsvm helper 2026-02-24 15:14:25 +02:00
Gani Georgiev eb28f898d0 [#7538] set OnlyInt:true when a view column expression is loosely known to return int-only values 2026-02-22 11:06:08 +02:00
Gani Georgiev ab0edb80df updated CHANGELOG 2026-02-21 13:31:48 +02:00
Gani Georgiev 233dd2ac67 bumped app version 2026-02-18 20:00:31 +02:00
Gani Georgiev 21d58d389f updated golang.org/x/ deps 2026-02-18 19:44:13 +02:00
Gani Georgiev 7f21e31145 updated modernc.org/sqlite to 1.46.1 2026-02-18 19:24:38 +02:00
Gani Georgiev 19ad2f3b04 [#7532] added compositionend listener 2026-02-17 18:20:07 +02:00
Gani Georgiev f6675702ea [#7532] pause collection and fields name normalization while in IME mode 2026-02-17 17:29:38 +02:00
Gani Georgiev 3b9f2141fe updated jsvm types 2026-02-16 22:04:19 +02:00
Gani Georgiev 2b39757fbc bumped app version 2026-02-16 21:08:13 +02:00
Gani Georgiev 15091999e3 use temp dir for the $filesystem.local test 2026-02-14 12:08:57 +02:00
Gani Georgiev fcc680794c [#7526] added $filesystem.s3 and $filesystem.local JSVM bindings 2026-02-14 11:49:50 +02:00
Gani Georgiev bc72525013 [#7525] made Bearer prefix case-insensitive 2026-02-14 11:19:13 +02:00
Gani Georgiev 23ca5a77e1 fixed changelog typo 2026-02-13 21:00:25 +02:00
Gani Georgiev 266b56ecbb updated goja deps 2026-02-13 20:07:31 +02:00
Gani Georgiev ac8a4583cb updated test status codes to 2xx due to go 1.26.0 stricter checks 2026-02-13 20:02:55 +02:00
Gani Georgiev 1d72c8487e bumped app version 2026-02-13 17:21:34 +02:00
Gani Georgiev 97eb9b300b renamed arguments to make it more clear that they are dangeous 2026-02-13 16:40:29 +02:00
Gani Georgiev 5b2cae8509 [#7523] added Accept-Encoding:identity to the S3 requests 2026-02-13 16:16:12 +02:00
Gani Georgiev 5715e11e52 bumped go deps 2026-02-11 15:02:38 +02:00
Gani Georgiev 90e9fa705d bumped app version 2026-02-01 09:40:10 +02:00
Gani Georgiev d4101be9f6 updated go deps 2026-02-01 09:34:17 +02:00
Gani Georgiev 6cec679f02 updated changelog 2026-01-28 11:52:56 +02:00
Gani Georgiev 0e0b862bd7 silenced race detector errors per #7484 2026-01-28 11:52:08 +02:00
Gani Georgiev b2bf26122f updated changelog 2026-01-27 16:53:09 +02:00
Gani Georgiev adc5c3cf18 updated goja 2026-01-27 16:51:55 +02:00
Gani Georgiev 4a1e3aed6e added extra collection field exist check to minimize misuse and have a more clear error message 2026-01-27 16:46:04 +02:00
Gani Georgiev 55e24344ff updated modernc.org/sqlite to v1.44.3 2026-01-23 00:44:23 +02:00
Gani Georgiev 17086722f4 updated thumb style and title for non-previewable files 2026-01-23 00:34:58 +02:00
Gani Georgiev 9b036fb10f updated modernc.org/sqlite to 1.44.2 2026-01-18 18:57:18 +02:00
Gani Georgiev 8e3f0f2e32 regenerated jsvm types and bumped app version 2026-01-18 18:53:03 +02:00
Gani Georgiev 65750bca8d revert GROUP BY optimization 2026-01-18 18:38:40 +02:00
Gani Georgiev adb991eb02 fixed comment typos 2026-01-17 10:58:12 +02:00
Gani Georgiev d87a887673 fixed docs link in the changelog 2026-01-16 06:55:02 +02:00
Gani Georgiev f2eb295fa2 updated modernc.org deps 2026-01-16 06:27:55 +02:00
Gani Georgiev d11a9f9d99 updated JSVM types and bumped app version 2026-01-15 22:24:07 +02:00
Gani Georgiev bbd7f4e4ae replaced NoCoalesce with NullFallback and updated tests 2026-01-15 18:06:15 +02:00
Gani Georgiev b0a5bce4c4 updated 0.35.1 changelog to reflect the modernc.org/sqlite 1.42.0 retraction and updated the driver to 1.44.0 2026-01-15 14:45:26 +02:00
Gani Georgiev 9234cbf0d1 updated changelog 2026-01-15 14:34:45 +02:00
Gani Georgiev 6bf5eccfa7 added strftime filter function 2026-01-15 14:27:53 +02:00
Gani Georgiev 8bbd0c2d77 updated changelog 2026-01-13 22:30:31 +02:00
Gani Georgiev 2af60a85c5 fixed typo and updated changelog 2026-01-13 22:23:23 +02:00
Gani Georgiev 56e53e885c added more UpdateQuery tests 2026-01-13 22:15:50 +02:00
Gani Georgiev 3115f08d4a updated ui version 2026-01-13 18:56:23 +02:00
Gani Georgiev 0b9a646d41 use group by instead of distinct when possible 2026-01-13 18:47:32 +02:00
Gani Georgiev 5f8cce3558 [#7444] remove unnecessery subquery when resolving single back-relation fields 2026-01-13 14:54:35 +02:00
Gani Georgiev 3da2c00f32 updated modernc.org/sqlite to 1.43.0 2026-01-10 10:57:33 +02:00
Gani Georgiev 352ee72740 normalized multiple to single field confirmation detection 2026-01-06 18:33:44 +02:00
Gani Georgiev 98510103c3 normalized relations picker maxSelect value 2026-01-06 18:19:01 +02:00
Gani Georgiev 25c044a3a2 updated changelog 2026-01-03 14:25:04 +02:00
Gani Georgiev 0536c779d5 updated modernc.org/sqlite to 1.42.2 2026-01-03 11:23:26 +02:00
Gani Georgiev b1da83e516 fixed comment typo 2025-12-21 09:24:07 +02:00
Gani Georgiev 6b5d7b216b bumped go deps and updated jsvm types 2025-12-21 08:11:36 +02:00
Gani Georgiev 26d6a98355 updated ui/dist 2025-12-19 19:25:08 +02:00
Gani Georgiev 4abc018d7c upgraded to math/rand/v2 2025-12-19 19:08:56 +02:00
Gani Georgiev f0a9cbf31b updated modernc.org/sqlite to v1.41.0 2025-12-19 17:11:21 +02:00
Gani Georgiev d08da7594a cap the file name before normalization 2025-12-19 16:58:08 +02:00
Gani Georgiev c2d6530065 added test for file name normalization with leading dot 2025-12-19 16:30:11 +02:00
Gani Georgiev 94c4d4ec65 removed legacy and unnecessery call 2025-12-19 10:49:34 +02:00
Gani Georgiev be7ec34516 fixed error msg typo 2025-12-19 10:19:31 +02:00
Gani Georgiev 27cb36ffd7 [#7396] added nullable JSVM type helpers 2025-12-17 19:27:17 +02:00
Gani Georgiev e7af58efac updated goja 2025-12-12 09:05:04 +02:00
Gani Georgiev ab51b3c038 updated ui/dist 2025-12-12 08:55:08 +02:00
Gani Georgiev 5773f46fea replace TrimSuffix with Trim 2025-12-12 08:52:22 +02:00
Gani Georgiev 4d5b7cc1d0 updated go deps 2025-12-12 08:50:33 +02:00
Gani Georgiev 7286f34104 trim normalized file extension 2025-12-12 08:49:10 +02:00
Gani Georgiev 4399a6c1ab added small threshold for the cron time based tests 2025-12-12 08:48:29 +02:00
Gani Georgiev e89603497f store the correct image/png as attrs content type when generating a thumb fallback 2025-12-09 17:09:32 +02:00
Gani Georgiev abb6bcd6de [#7369] bumped JS SDK to fix Safari AbortError detection introduced with the previous release 2025-12-04 14:46:28 +02:00
Gani Georgiev 5604fe672e updated changelog 2025-12-02 20:20:41 +02:00
Gani Georgiev 7825baab13 updated v0.22 changelog and bumped actions/setup-go to v6 2025-12-02 20:20:27 +02:00
Gani Georgiev 68b9d0e403 updated go deps and bumped min go github version 2025-12-02 19:28:27 +02:00
Gani Georgiev 85232ed6e4 updated js sdk 2025-12-02 19:23:21 +02:00
Gani Georgiev d76d4089cf [#7357] added Copy raw JSON collection dropdown option 2025-12-02 08:21:20 +02:00
Gani Georgievandjb.muscat 2e5f8bff63 [#7353] added missing : char to the autocomplete regex
Co-authored-by: jb.muscat <jb.muscat@criteo.com>
2025-12-02 07:56:54 +02:00
Gani Georgiev 90d896e1cc updated changelog 2025-11-22 10:59:25 +02:00
Gani Georgiev c13d83adb1 updated jsvm types 2025-11-22 10:59:15 +02:00
Gani Georgiev 9b73295a7c added dumy request info to directly return an error on invalid API rule 2025-11-22 10:58:32 +02:00
Gani Georgiev 3c6ce2de74 updated go deps 2025-11-22 09:36:50 +02:00
Gani Georgiev 63b89533a9 use TEST_IP for the test auth alert email 2025-11-22 09:36:20 +02:00
Gani Georgiev 779059eca3 added short info about the backup restore steps 2025-11-22 09:36:02 +02:00
Gani Georgiev 9abdadf0dc updated modernc.org/sqlite 2025-11-18 22:24:49 +02:00
Gani Georgiev 6500b8c518 renamed outdated rate limit struct name and added reminder to reavulate the algorithm 2025-11-18 22:23:59 +02:00
Stephen Daves 91f1ca273d [#7333] updated CHANGELOG with typo fixed for geoDistance url 2025-11-18 07:39:28 +02:00
Gani Georgiev 6e739fd33d added :changed request body modifier 2025-11-17 13:58:43 +02:00
Gani Georgiev 2525f29c1c adde auth alert info as OnMailerRecordAuthAlertSend meta 2025-11-15 21:21:06 +02:00
Gani Georgiev 1dc5e061b8 updated changelog and ui/dist 2025-11-13 15:51:51 +02:00
Gani Georgiev 09d7f6a7c3 added missing mails.sendRecordAuthAlert jsvm binding 2025-11-13 10:45:33 +02:00
Gani Georgiev 1775585b68 updated goja and migrate timestamp 2025-11-13 09:59:14 +02:00
Gani Georgiev f4e6c5edee updated x/sync and other go deps 2025-11-12 15:17:36 +02:00
Gani Georgiev 94b11bf2c3 added test for escaped alert info 2025-11-12 15:15:54 +02:00
Gani Georgiev ddb8c88a37 replaced placeholder in migration and updated jsvm types 2025-11-10 17:59:11 +02:00
Gani Georgiev 0f5411d81c [#7314] added ALERT_INFO placeholder to the auth alert mail template 2025-11-10 17:56:36 +02:00
Gani Georgiev 423d234da1 added pk test for * character 2025-11-10 07:17:01 +02:00
Gani Georgiev 6184b31d82 [#7312] added extra id validations 2025-11-09 15:24:24 +02:00
Gani Georgiev 63a9d045a1 [#7312] excluded id from the excerpt list 2025-11-08 23:32:30 +02:00
Gani Georgiev 501ab0e6be updated modernc.org/sqlite to 1.40.0 2025-11-08 11:17:26 +02:00
Gani Georgiev 7ad08ef6bf updated changelog 2025-11-08 10:57:22 +02:00
Gani Georgiev 6210f361b0 bumped app version and updated ui/dist 2025-11-08 10:49:41 +02:00
Gani GeorgievandFelix fcb5b5dd67 [#7305] fixed deadlock when manually triggering the OnTerminate hook
Co-authored-by: Felix <FelixM@yer.tools>
2025-11-07 17:03:15 +02:00
Gani Georgiev 41607679a0 updated readme 2025-11-04 13:03:30 +02:00
Gani Georgiev ca7e5b7f7b updated jsvm types 2025-11-04 11:23:35 +02:00
Gani Georgiev 593721dcea flatten relation joins 2025-11-03 14:21:01 +02:00
Gani Georgiev 153ad12e64 set allowHiddenFields to prevent infinite recursion 2025-11-01 14:54:22 +02:00
Gani Georgiev 482fe2bce0 updated ui/dist 2025-10-31 22:41:52 +02:00
Gani Georgiev 48489b6a07 updated jsvm types 2025-10-31 22:24:47 +02:00
Gani Georgiev 67ee431585 add extra subquery check for client-side relation filtering 2025-10-31 22:22:28 +02:00
Gani Georgiev d5dcd01551 updated ui/dist 2025-10-23 22:33:12 +03:00
Gani Georgiev 749bf7815c updated changelog 2025-10-23 20:28:13 +03:00
Gani Georgiev ceae5e005f updated jsvm types and npm deps 2025-10-23 18:21:34 +03:00
Gani Georgiev 7b6b71e18d disallow client-side filtering and sorting of relations where the collection of the last targeted field has superusers only List/Search API rule 2025-10-23 17:22:47 +03:00
Gani Georgiev 885d907beb updated jsvm types 2025-10-23 13:15:03 +03:00
Gani Georgiev afb942bc41 updated thumb error message 2025-10-23 11:55:19 +03:00
Gani Georgiev 83a26d436e [#7268] added FileDownloadRequestEvent.ThumbError field 2025-10-23 11:48:59 +03:00
Gani Georgiev 7b52d0b56a [#7267] added tests.ApiScenario.DisableTestAppCleanup optional field 2025-10-23 11:13:49 +03:00
Gani Georgiev 5a8eae7089 add fallback in case the collection name in the response was stripped 2025-10-23 10:55:04 +03:00
Gani Georgiev 0bd712752f moved ValidateTokenSignature to jwk and added tests 2025-10-19 18:19:26 +03:00
Gani Georgiev 0b6157e1cc added no bounties note in the security policy 2025-10-19 15:49:10 +03:00
Gani Georgiev c8980edf85 updated npm deps 2025-10-19 15:41:07 +03:00
Gani Georgiev a7ebb98e20 wrap record info fields separatedly from link btn 2025-10-19 15:38:21 +03:00
Gani Georgiev 69be986132 limit max expanded presentable relations to 2 2025-10-19 14:03:28 +03:00
Gani Georgiev 58da159641 [#7252] support ed25519 oidc id_token signature validation 2025-10-19 13:49:39 +03:00
Gani Georgiev 8acb48b884 updated record-info-excerpt styles 2025-10-17 19:11:21 +03:00
Gani Georgiev 91b521595a [#7260] print nested presentable multiple relation fields 2025-10-17 14:43:36 +03:00
Gani Georgiev 52a53b5b91 updated ui/dist 2025-10-17 10:47:48 +03:00
Gani Georgiev 1137a35ded unify code-editor wrapper fields padding 2025-10-17 10:45:24 +03:00
Gani Georgiev 280005e35c [#7259] fixed json field overflow 2025-10-17 10:27:04 +03:00
Gani Georgiev 6656d9820a [#7223] workaround firefox overflow issue 2025-10-15 20:31:40 +03:00
Gani Georgiev 0d8b426b0c updated modernc.org/sqlite 2025-10-15 20:27:35 +03:00
Gani Georgiev acd12ce9dd [#7256] fixed legacy identitity field priority check when a username is a valid email address 2025-10-15 17:25:51 +03:00
Gani Georgiev 47d3da28d5 updated supported modernc.org build targets list 2025-10-08 20:08:16 +03:00
Gani Georgiev 6f8524961f updated go deps 2025-10-08 19:44:46 +03:00
1021 changed files with 73302 additions and 58688 deletions
+125 -2
View File
@@ -1,5 +1,128 @@
# Security
If you discover a security vulnerability within PocketBase, please send an e-mail to **support at pocketbase.io**.
**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!**
All reports will be promptly addressed and you'll be credited in the fix release notes.
If you want to responsibly report a security issue you'll have to reach out as a human to **support at pocketbase.io**.
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
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))_.
**Or in other words - a simple _"Hey I think I found a security issue when I do X"_ is enough.**
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.
In case the vulnerability is confirmed:
- 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:
<details>
<summary><strong>Stored XSS</strong></summary>
This was discussed several times, both privately and [publicly](https://github.com/pocketbase/pocketbase/discussions/6694), but I remain on the opinion that it should be handled primarily on the client-side.
Modern browsers recently introduced a basic [`Sanitizer` interface](https://developer.mozilla.org/en-US/docs/Web/API/Sanitizer) that could help filtering HTML strings without external libraries.
Having also a default [Content Security Policy (CSP)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP) either as meta tag or response header is always a good idea to minimize the risk of XSS.
</details>
<details>
<summary><strong>SQL injection in low level DB methods like <code>app.DeleteTable(dangerousName)</code></strong></summary>
This is working correctly and it is not an issue but it is a common report most likely found by LLM or some other automated tools that may have stumbled on the [NB! code comments](https://pkg.go.dev/github.com/pocketbase/pocketbase@master/core#BaseApp.DeleteTable).
Raw SQL statements, table and column names are not parameterized and they are vulnerable to SQL injection if used with untrusted input. The documentation as seen above already warns against it. In recent PocketBase releases, many of the arguments of these methods were also prefixed with `dangerous*` to make it even more clear that they should be used with caution.
</details>
<details>
<summary><strong>Race conditions</strong></summary>
To avoid DB locks PocketBase deliberately tries to minimize the use of DB transactions.
This means that operations like record update don't wrap out of the box for example the `SELECT` and `UPDATE` SQL statements in a single transaction, and this can technically lead to a race condition if multiple users edit the same record.
This is an accepted tradeoff and for the majority of cases it has no security implications.
This also apply for the read and delete of MFA and OTP records but for those cases, since they operate in a security sensitive context, they have an extra short-lived duration that is configurable from the collection settings _(there are also system cron jobs that takes care for deleting forgotten/expired entries to prevent accumulation of invalid records)_.
For the cases where transactions are really needed, users can utilize the [Batch Web API](https://pocketbase.io/docs/api-records/#batch-createupdateupsertdelete-records) or [create a transaction programmatically](https://pocketbase.io/docs/go-records/#transaction) _(with PocketBase v0.23+ it is also possible to wrap an entire hook chain in a single transaction)_.
</details>
<details>
<summary><strong>List/Search side-channel attacks</strong></summary>
Over the years we've implemented several extra checks to minimize the risk of List/Search side-channel attacks (see especially [v0.32.0](https://github.com/pocketbase/pocketbase/blob/master/CHANGELOG.md#v0320)) but users need to be aware that all client-side filtered fields are technically subject to timing attacks _(whether they are practical or not is a different topic)_.
This is by design and it is accepted tradeoff between performance, security and usability.
If you are concerned about timing attacks and have security sensitive collection data such as `secret`, `code`, `token`, etc. then the general recommendation is to mark their related fields as "Hidden" in order to disallow use in client-side filters.
</details>
<details>
<summary><strong>Connecting to a vulnerable OAuth2 provider</strong></summary>
Because PocketBase v0.23+ supports automatically uploading the OAuth2 avatar on user create _(need to be specified from the auth collection OAuth2 fields mapping)_ some security researchers raised a concern regarding a Blind SSRF but this implies that an attacker controls the OAuth2 vendor and this is a very serious assumption in the first place.
The entire OAuth2 flow relies that the application server (PocketBase) trusts the configured OAuth2 vendor.
If you suspect that an OAuth2 vendor is malicious and cannot be trusted then you MUST NOT use that OAuth2 vendor at all and you should report it.
If someone is able to tamper with the OAuth2 responses then the entire OAuth2 flow can be thrown out of the window because they will be practically able to authenticate as any of your existing users and the eventual avatar URL probing request is the least of your problem.
~Nonetheless, in future PocketBase releases there will be [extra `localhost` domain like checks](https://github.com/orgs/pocketbase/projects/2/views/1?pane=issue&itemId=159545722) when assigning the OAuth2 avatar URL to a `file` field that will further minimize the risk of internal network probing requests in case of a vulnerable OAuth2 provider.~ _Done._
</details>
<details>
<summary><strong>Users enumeration</strong></summary>
This is a common and usually valid report but there is no easy solution without confusing and degrading the users experience.
Some endpoints, like the user create/register, can be used for usernames or emails enumeration based on various response heuristics - timing, specific error messages, etc.
In many places where applicable we've tried to minimize the impact by using constant time checks, returning non-descriptive error messages, applying an internal rate limit for some operations, etc. but it is not bulletproof and if somebody wants to find out if a user is registered they will be able to do it one way or another.
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>
Just for the past month, due to some corporate security scanners 5 different people raised concerns over [CVE-2023-36308](https://nvd.nist.gov/vuln/detail/CVE-2023-36308) but this is not really a vulnerability, especially not in PocketBase.
[`disintegration/imaging`](https://github.com/disintegration/imaging) is a direct PocketBase dependency responsible for the thumbs generation.
First, a panic (similar to exception in other languages) is NOT a security issue and Go programs usually have to be written defensively with that in mind. In PocketBase specifically all routes have auto panic-recover handling, no matter what the source of the panic is, so the worst case scenario would be an HTTP error response when attempting to access the thumb.
Second, the related issue that the CVE describes is probably caused by a bug in an outdated `golang.org/x/image` dependency listed in the `go.mod` of that package but PocketBase uses a newer patched version of it that is expected to take precedence.
Third, even if that issue is still available, with PocketBase it would have been triggerable ONLY if we supported TIFF thumbs generation but we don't. The supported thumbs formats at the moment are JPG, PNG, GIF (its first frame) and partially WebP (stored as PNG). All other images are served as it is, without any transformation.
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>
+5 -5
View File
@@ -16,19 +16,19 @@ jobs:
run: echo "flags=--snapshot" >> $GITHUB_ENV
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Set up Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version: 20.17.0
node-version: '>=25.2.1'
- name: Set up Go
uses: actions/setup-go@v5
uses: actions/setup-go@v7
with:
go-version: '>=1.24.8'
go-version: '>=1.27.1'
# 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.
+34 -652
View File
@@ -1,674 +1,56 @@
## v0.30.2
## v0.40.2
- Bumped min Go GitHub action version to 1.24.8 since it comes with some [minor security fixes](https://github.com/golang/go/issues?q=milestone%3AGo1.24.8+label%3ACherryPickApproved).
- Return an error when filter params fallback fails to json serialize and optimized params replacement to execute in a single pass.
- Fixed collection index parsing error for indexes with missing name.
## v0.30.1
- Minor UI autocomplete optimizations _(prefix match, autocomplete debounce, etc.)_.
- ⚠️ Excluded the `lost+found` directory from the backups ([#7208](https://github.com/pocketbase/pocketbase/pull/7208); thanks @lbndev).
_If for some reason you want to keep it, you can restore it by editing the `e.Exclude` list of the `OnBackupCreate` and `OnBackupRestore` hooks._
- Fixed linter warnings and comment typos.
- Minor tests improvements (disabled initial superuser creation for the test app to avoid cluttering the std output, added more tests for the `s3.Uploader.MaxConcurrency`, etc.).
- Bumped goja and its related dependencies _(regex unescaped dash error fix and base64 optimizations)_.
- Updated `modernc.org/sqlite` and other Go dependencies.
- Bumped the min Go GitHub action version to 1.27.1 as it includes some [minor `database/sql` and `enconding/json/v2` bug fixes](https://github.com/golang/go/issues?q=milestone%3AGo1.27.1).
## v0.30.0
## v0.40.1
- Eagerly escape the S3 request path following the same rules as in the S3 signing header ([#7153](https://github.com/pocketbase/pocketbase/issues/7153)).
- Fixes for some reported regressions related to the `encoding/json/v2` update:
- allow mangling invalid UTF8 characters when serializing json data ([#7814](https://github.com/pocketbase/pocketbase/issues/7814))
- fixed OAuth2 providers config merge incorrectly replacing the entire slice ([#7815](https://github.com/pocketbase/pocketbase/issues/7815))
- Added Lark OAuth2 provider ([#7130](https://github.com/pocketbase/pocketbase/pull/7130); thanks @mashizora).
- Increased test tokens `exp` claim to minimize eventual issues with reproducible builds ([#7123](https://github.com/pocketbase/pocketbase/issues/7123)).
## v0.40.0
- Added `os.Root` bindings to the JSVM ([`$os.openRoot`](https://pocketbase.io/jsvm/functions/_os.openRoot.html), [`$os.openInRoot`](https://pocketbase.io/jsvm/functions/_os.openInRoot.html)).
- Propagate console command errors and recovered panics to `app.Start()` so that the program can exit with non-zero code while still ensuring that `app.OnTerminate` hook was triggered _(responsible for the app graceful shutdown handling)_.
_⚠️ Note that this could be a slight breaking change in case you are chaining PocketBase commands and relied on the previous `0` exit status for `Command.RunE` returned errors._
_Or in other words, if you have `./pocketbase invalid && someothercommand` and previously relied that `someothercommand` will be always executed then this is no longer the case and you'll have to adjust it or replace `&&` with `;`._
- Added `osutils.IsProbablyGoRun()` helper to loosely check if the program was started using `go run`.
- Added quotes around the default `Content-Disposition` serving filename in case custom name with special characters is provided.
- Various minor UI improvements (updated collections indexes UI, enabled seconds in the datepicker, updated helper texts, etc.).
- Added `Cross-Origin-Opener-Policy:same-origin` to the default security response headers.
_This is an extra precaution to prevent tab-nabbing in case custom UI plugins use `target="_blank"` without `rel="noopener"`._
- ⚠️ Updated the minimum package Go version to 1.24.0 and bumped Go dependencies.
- Added `Record.GetInt64(field)` helper (note that the serializable max safe integer of the `number` field is ~2^53-1).
- Added `Store.Keys()` method that returns a slice with all of the store keys.
## v0.29.3
- Added new `DELETE /api/logs` endpoint and UI control to delete all logs without changing the `maxDays` retention setting.
- Try to forward Apple OAuth2 POST redirect user's name so that it can be returned (and eventually assigned) with the success response of the all-in-one auth call ([#7090](https://github.com/pocketbase/pocketbase/issues/7090)).
- Added new log settings option to limit the max `Log.Data` size that will be saved in the database (default to ~16KB).
_This is an extra precaution for the cases when logging user supplied data without validating it beforehand._
_If the resulting `Log.Data` json is above the limit, it is truncated to the last valid decoded character and an extra `"__pb_truncated__":true` log data entry will be added.`_
_Additionally, for just in case the log message is also truncated at max 8k characters._
- Fixed `RateLimitRule.Audience` code comment ([#7098](https://github.com/pocketbase/pocketbase/pull/7098); thanks @iustin05).
- Added new `filesystem` low-level helper methods:
- `filesystem.NewWriter(key, opts)` to allow direct file create from an `io.Reader` value.
- `filesystem.OnNewWriter()` hook to allow listening for new/to-be-created files _(it is not exposed in `core.App` instance for now to avoid introducing breaking changes)_.
- `filesystem.OnDelete()` hook to allow listening for deleted files _(it is not exposed in `core.App` instance for now to avoid introducing breaking changes)_.
- Mocked `syscall.Exec` when building for WASM ([#7116](https://github.com/pocketbase/pocketbase/pull/7116); thanks @joas8211).
_Note that WASM is not officially supported PocketBase build target and many things may not work as expected._
- Optimized backups to no longer transaction lock the database during backup generation ([#7799](https://github.com/pocketbase/pocketbase/discussions/7799#discussioncomment-18108244)).
- Registered missing `$filesystem`, `$mails`, `$template` and `__hooks` bindings in the JSVM migrations ([#7125](https://github.com/pocketbase/pocketbase/issues/7125)).
- Updated `modernc.org/sqlite` to 1.57.0 and registered by default the new `_defensive=1` DSN query parameter to enable [SQLite's defensive mode](https://sqlite.org/c3ref/c_dbconfig_defensive.html#sqlitedbconfigdefensive).
- Regenerated JSVM types to include methods from structs with single generic parameter.
- Updated Go dependencies.
## v0.29.2
- Bumped min Go GitHub action version to 1.23.12 since it comes with some [minor fixes for the runtime and `database/sql` package](https://github.com/golang/go/issues?q=milestone%3AGo1.23.12+label%3ACherryPickApproved).
## v0.29.1
- Updated the X/Twitter provider to return the `confirmed_email` field and to use the `x.com` domain ([#7035](https://github.com/pocketbase/pocketbase/issues/7035)).
- Added Box.com OAuth2 provider ([#7056](https://github.com/pocketbase/pocketbase/pull/7056); thanks @blakepatteson).
- Updated `modernc.org/sqlite` to 1.38.2 (SQLite 3.50.3).
- Fixed example List API response ([#7049](https://github.com/pocketbase/pocketbase/pull/7049); thanks @williamtguerra).
## v0.29.0
- Enabled calling the `/auth-refresh` endpoint with nonrenewable tokens.
_When used with nonrenewable tokens (e.g. impersonate) the endpoint will simply return the same token with the up-to-date user data associated with it._
- Added the triggered rate rimit rule in the error log `details`.
- Added optional `ServeEvent.Listener` field to initialize a custom network listener (e.g. `unix`) instead of the default `tcp` ([#3233](https://github.com/pocketbase/pocketbase/discussions/3233)).
- Fixed request data unmarshalization for the `DynamicModel` array/object fields ([#7022](https://github.com/pocketbase/pocketbase/discussions/7022)).
- Fixed Dashboard page title `-` escaping ([#6982](https://github.com/pocketbase/pocketbase/issues/6982)).
- Other minor improvements (updated first superuser console text when running with `go run`, clarified trusted IP proxy header label, wrapped the backup restore in a transaction as an extra precaution, updated deps, etc.).
## v0.28.4
- Added global JSVM `toBytes()` helper to return the bytes slice representation of a value such as io.Reader or string, _other types are first serialized to Go string_ ([#6935](https://github.com/pocketbase/pocketbase/issues/6935)).
- Fixed `security.RandomStringByRegex` random distribution ([#6947](https://github.com/pocketbase/pocketbase/pull/6947); thanks @yerTools).
- Minor docs and typos fixes.
## v0.28.3
- Skip sending empty `Range` header when fetching blobs from S3 ([#6914](https://github.com/pocketbase/pocketbase/pull/6914)).
- Updated Go deps and particularly `modernc.org/sqlite` to 1.38.0 (SQLite 3.50.1).
- Bumped GitHub action min Go version to 1.23.10 as it comes with some [minor security `net/http` fixes](https://github.com/golang/go/issues?q=milestone%3AGo1.23.10+label%3ACherryPickApproved).
## v0.28.2
- Loaded latin-ext charset for the default text fonts ([#6869](https://github.com/pocketbase/pocketbase/issues/6869)).
- Updated view query CAST regex to properly recognize multiline expressions ([#6860](https://github.com/pocketbase/pocketbase/pull/6860); thanks @azat-ismagilov).
- Updated Go and npm dependencies.
## v0.28.1
- Fixed `json_each`/`json_array_length` normalizations to properly check for array values ([#6835](https://github.com/pocketbase/pocketbase/issues/6835)).
## v0.28.0
- Write the default response body of `*Request` hooks that are wrapped in a transaction after the related transaction completes to allow propagating the transaction error ([#6462](https://github.com/pocketbase/pocketbase/discussions/6462#discussioncomment-12207818)).
- Updated `app.DB()` to automatically routes raw write SQL statements to the nonconcurrent db pool ([#6689](https://github.com/pocketbase/pocketbase/discussions/6689)).
_For the rare cases when it is needed users still have the option to explicitly target the specific pool they want using `app.ConcurrentDB()`/`app.NonconcurrentDB()`._
- ⚠️ Changed the default `json` field max size to 1MB.
_Users still have the option to adjust the default limit from the collection field options but keep in mind that storing large strings/blobs in the database is known to cause performance issues and should be avoided when possible._
- ⚠️ Soft-deprecated and replaced `filesystem.System.GetFile(fileKey)` with `filesystem.System.GetReader(fileKey)` to avoid the confusion with `filesystem.File`.
_The old method will still continue to work for at least until v0.29.0 but you'll get a console warning to replace it with `GetReader`._
- Added new `filesystem.System.GetReuploadableFile(fileKey, preserveName)` method to return an existing blob as a `*filesystem.File` value ([#6792](https://github.com/pocketbase/pocketbase/discussions/6792)).
_This method could be useful in case you want to clone an existing Record file and assign it to a new Record (e.g. in a Record duplicate action)._
- Other minor improvements (updated the GitHub release min Go version to 1.23.9, updated npm and Go deps, etc.)
## v0.27.2
- Added workers pool when cascade deleting record files to minimize _"thread exhaustion"_ errors ([#6780](https://github.com/pocketbase/pocketbase/discussions/6780)).
- Updated the `:excerpt` fields modifier to properly account for multibyte characters ([#6778](https://github.com/pocketbase/pocketbase/issues/6778)).
- Use `rowid` as count column for non-view collections to minimize the need of having the id field in a covering index ([#6739](https://github.com/pocketbase/pocketbase/discussions/6739))
## v0.27.1
- Updated example `geoPoint` API preview body data.
- Added JSVM `new GeoPointField({ ... })` constructor.
- Added _partial_ WebP thumbs generation (_the thumbs will be stored as PNG_; [#6744](https://github.com/pocketbase/pocketbase/pull/6744)).
- Updated npm dev dependencies.
## v0.27.0
- ⚠️ Moved the Create and Manage API rule checks out of the `OnRecordCreateRequest` hook finalizer, **aka. now all CRUD API rules are checked BEFORE triggering their corresponding `*Request` hook**.
This was done to minimize the confusion regarding the firing order of the request operations, making it more predictable and consistent with the other record List/View/Update/Delete request actions.
It could be a minor breaking change if you are relying on the old behavior and have a Go `tests.ApiScenario` that is testing a Create API rule failure and expect `OnRecordCreateRequest` to be fired. In that case for example you may have to update your test scenario like:
```go
tests.ApiScenario{
Name: "Example test that checks a Create API rule failure"
Method: http.MethodPost,
URL: "/api/collections/example/records",
...
// old:
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordCreateRequest": 1,
},
// new:
ExpectedEvents: map[string]int{"*": 0},
}
```
If you are having difficulties adjusting your code, feel free to open a [Q&A discussion](https://github.com/pocketbase/pocketbase/discussions) with the failing/problematic code sample.
- Added [new `geoPoint` field](https://pocketbase.io/docs/collections/#geopoint) for storing `{"lon":x,"lat":y}` geographic coordinates.
In addition, a new [`geoDistance(lonA, lotA, lonB, lotB)` function](htts://pocketbase.io/docs/api-rules-and-filters/#geodistancelona-lata-lonb-latb) was also implemented that could be used to apply an API rule or filter constraint based on the distance (in km) between 2 geo points.
- Updated the `select` field UI to accommodate better larger lists and RTL languages ([#4674](https://github.com/pocketbase/pocketbase/issues/4674)).
- Updated the mail attachments auto MIME type detection to use `gabriel-vasile/mimetype` for consistency and broader sniffing signatures support.
- Forced `text/javascript` Content-Type when serving `.js`/`.mjs` collection uploaded files with the `/api/files/...` endpoint ([#6597](https://github.com/pocketbase/pocketbase/issues/6597)).
- Added second optional JSVM `DateTime` constructor argument for specifying a default timezone as TZ identifier when parsing the date string as alternative to a fixed offset in order to better handle daylight saving time nuances ([#6688](https://github.com/pocketbase/pocketbase/discussions/6688)):
```js
// the same as with CET offset: new DateTime("2025-10-26 03:00:00 +01:00")
new DateTime("2025-10-26 03:00:00", "Europe/Amsterdam") // 2025-10-26 02:00:00.000Z
// the same as with CEST offset: new DateTime("2025-10-26 01:00:00 +02:00")
new DateTime("2025-10-26 01:00:00", "Europe/Amsterdam") // 2025-10-25 23:00:00.000Z
```
- Soft-deprecated the `$http.send`'s `result.raw` field in favor of `result.body` that contains the response body as plain bytes slice to avoid the discrepancies between Go and the JSVM when casting binary data to string.
- Updated `modernc.org/sqlite` to 1.37.0.
- Other minor improvements (_removed the superuser fields from the auth record create/update body examples, allowed programmatically updating the auth record password from the create/update hooks, fixed collections import error response, etc._).
## v0.26.6
- Allow OIDC `email_verified` to be int or boolean string since some OIDC providers like AWS Cognito has non-standard userinfo response ([#6657](https://github.com/pocketbase/pocketbase/pull/6657)).
- Updated `modernc.org/sqlite` to 1.36.3.
## v0.26.5
- Fixed canonical URI parts escaping when generating the S3 request signature ([#6654](https://github.com/pocketbase/pocketbase/issues/6654)).
## v0.26.4
- Fixed `RecordErrorEvent.Error` and `CollectionErrorEvent.Error` sync with `ModelErrorEvent.Error` ([#6639](https://github.com/pocketbase/pocketbase/issues/6639)).
- Fixed logs details copy to clipboard action.
- Updated `modernc.org/sqlite` to 1.36.2.
## v0.26.3
- Fixed and normalized logs error serialization across common types for more consistent logs error output ([#6631](https://github.com/pocketbase/pocketbase/issues/6631)).
## v0.26.2
- Updated `golang-jwt/jwt` dependency because it comes with a [minor security fix](https://github.com/golang-jwt/jwt/security/advisories/GHSA-mh63-6h87-95cp).
## v0.26.1
- Removed the wrapping of `io.EOF` error when reading files since currently `io.ReadAll` doesn't check for wrapped errors ([#6600](https://github.com/pocketbase/pocketbase/issues/6600)).
## v0.26.0
- ⚠️ Replaced `aws-sdk-go-v2` and `gocloud.dev/blob` with custom lighter implementation ([#6562](https://github.com/pocketbase/pocketbase/discussions/6562)).
As a side-effect of the dependency removal, the binary size has been reduced with ~10MB and builds ~30% faster.
_Although the change is expected to be backward-compatible, I'd recommend to test first locally the new version with your S3 provider (if you use S3 for files storage and backups)._
- ⚠️ Prioritized the user submitted non-empty `createData.email` (_it will be unverified_) when creating the PocketBase user during the first OAuth2 auth.
- Load the request info context during password/OAuth2/OTP authentication ([#6402](https://github.com/pocketbase/pocketbase/issues/6402)).
This could be useful in case you want to target the auth method as part of the MFA and Auth API rules.
For example, to disable MFA for the OAuth2 auth could be expressed as `@request.context != "oauth2"` MFA rule.
- Added `store.Store.SetFunc(key, func(old T) new T)` to set/update a store value with the return result of the callback in a concurrent safe manner.
- Added `subscription.Message.WriteSSE(w, id)` for writing an SSE formatted message into the provided writer interface (_used mostly to assist with the unit testing_).
- Added `$os.stat(file)` JSVM helper ([#6407](https://github.com/pocketbase/pocketbase/discussions/6407)).
- Added log warning for `async` marked JSVM handlers and resolve when possible the returned `Promise` as fallback ([#6476](https://github.com/pocketbase/pocketbase/issues/6476)).
- Allowed calling `cronAdd`, `cronRemove` from inside other JSVM handlers ([#6481](https://github.com/pocketbase/pocketbase/discussions/6481)).
- Bumped the default request read and write timeouts to 5mins (_old 3mins_) to accommodate slower internet connections and larger file uploads/downloads.
_If you want to change them you can modify the `OnServe` hook's `ServeEvent.ReadTimeout/WriteTimeout` fields as shown in [#6550](https://github.com/pocketbase/pocketbase/discussions/6550#discussioncomment-12364515)._
- Normalized the `@request.auth.*` and `@request.body.*` back relations resolver to always return `null` when the relation field is pointing to a different collection ([#6590](https://github.com/pocketbase/pocketbase/discussions/6590#discussioncomment-12496581)).
- Other minor improvements (_fixed query dev log nested parameters output, reintroduced `DynamicModel` object/array props reflect types caching, updated Go and npm deps, etc._)
## v0.25.9
- Fixed `DynamicModel` object/array props reflect type caching ([#6563](https://github.com/pocketbase/pocketbase/discussions/6563)).
## v0.25.8
- Added a default leeway of 5 minutes for the Apple/OIDC `id_token` timestamp claims check to account for clock-skew ([#6529](https://github.com/pocketbase/pocketbase/issues/6529)).
It can be further customized if needed with the `PB_ID_TOKEN_LEEWAY` env variable (_the value must be in seconds, e.g. "PB_ID_TOKEN_LEEWAY=60" for 1 minute_).
## v0.25.7
- Fixed `@request.body.jsonObjOrArr.*` values extraction ([#6493](https://github.com/pocketbase/pocketbase/discussions/6493)).
## v0.25.6
- Restore the missing `meta.isNew` field of the OAuth2 success response ([#6490](https://github.com/pocketbase/pocketbase/issues/6490)).
- Updated npm dependencies.
## v0.25.5
- Set the current working directory as a default goja script path when executing inline JS strings to allow `require(m)` traversing parent `node_modules` directories.
- Updated `modernc.org/sqlite` and `modernc.org/libc` dependencies.
## v0.25.4
- Downgraded `aws-sdk-go-v2` to the version before the default data integrity checks because there have been reports for non-AWS S3 providers in addition to Backblaze (IDrive, R2) that no longer or partially work with the latest AWS SDK changes.
While we try to enforce `when_required` by default, it is not enough to disable the new AWS SDK integrity checks entirely and some providers will require additional manual adjustments to make them compatible with the latest AWS SDK (e.g. removing the `x-aws-checksum-*` headers, unsetting the checksums calculation or reinstantiating the old MD5 checksums for some of the required operations, etc.) which as a result leads to a configuration mess that I'm not sure it would be a good idea to introduce.
This unfornuatelly is not a PocketBase or Go specific issue and the official AWS SDKs for other languages are in the same situation (even the latest aws-cli).
For those of you that extend PocketBase with Go: if your S3 vendor doesn't support the [AWS Data integrity checks](https://docs.aws.amazon.com/sdkref/latest/guide/feature-dataintegrity.html) and you are updating with `go get -u`, then make sure that the `aws-sdk-go-v2` dependencies in your `go.mod` are the same as in the repo:
```
// go.mod
github.com/aws/aws-sdk-go-v2 v1.36.1
github.com/aws/aws-sdk-go-v2/config v1.28.10
github.com/aws/aws-sdk-go-v2/credentials v1.17.51
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.17.48
github.com/aws/aws-sdk-go-v2/service/s3 v1.72.2
// after that run
go clean -modcache && go mod tidy
```
_The versions pinning is temporary until the non-AWS S3 vendors patch their implementation or until I manage to find time to remove/replace the `aws-sdk-go-v2` dependency (I'll consider prioritizing it for the v0.26 or v0.27 release)._
## v0.25.3
- Added a temporary exception for Backblaze S3 endpoints to exclude the new `aws-sdk-go-v2` checksum headers ([#6440](https://github.com/pocketbase/pocketbase/discussions/6440)).
## v0.25.2
- Fixed realtime delete event not being fired for `RecordProxy`-ies and added basic realtime record resolve automated tests ([#6433](https://github.com/pocketbase/pocketbase/issues/6433)).
## v0.25.1
- Fixed the batch API Preview success sample response.
- Bumped GitHub action min Go version to 1.23.6 as it comes with a [minor security fix](https://github.com/golang/go/issues?q=milestone%3AGo1.23.6+label%3ACherryPickApproved) for the ppc64le build.
## v0.25.0
- ⚠️ Upgraded Google OAuth2 auth, token and userinfo endpoints to their latest versions.
_For users that don't do anything custom with the Google OAuth2 data or the OAuth2 auth URL, this should be a non-breaking change. The exceptions that I could find are:_
- `/v3/userinfo` auth response changes:
```
meta.rawUser.id => meta.rawUser.sub
meta.rawUser.verified_email => meta.rawUser.email_verified
```
- `/v2/auth` query parameters changes:
If you are specifying custom `approval_prompt=force` query parameter for the OAuth2 auth URL, you'll have to replace it with **`prompt=consent`**.
- Added Trakt OAuth2 provider ([#6338](https://github.com/pocketbase/pocketbase/pull/6338); thanks @aidan-)
- Added support for case-insensitive password auth based on the related UNIQUE index field collation ([#6337](https://github.com/pocketbase/pocketbase/discussions/6337)).
- Enforced `when_required` for the new AWS SDK request and response checksum validations to allow other non-AWS vendors to catch up with new AWS SDK changes (see [#6313](https://github.com/pocketbase/pocketbase/discussions/6313) and [aws/aws-sdk-go-v2#2960](https://github.com/aws/aws-sdk-go-v2/discussions/2960)).
_You can set the environment variables `AWS_REQUEST_CHECKSUM_CALCULATION` and `AWS_RESPONSE_CHECKSUM_VALIDATION` to `when_supported` if your S3 vendor supports the [new default integrity protections](https://docs.aws.amazon.com/sdkref/latest/guide/feature-dataintegrity.html)._
- Soft-deprecated `Record.GetUploadedFiles` in favor of `Record.GetUnsavedFiles` to minimize the ambiguities what the method do ([#6269](https://github.com/pocketbase/pocketbase/discussions/6269)).
- Replaced archived `github.com/AlecAivazis/survey` dependency with a simpler `osutils.YesNoPrompt(message, fallback)` helper.
- Upgraded to `golang-jwt/jwt/v5`.
- Added JSVM `new Timezone(name)` binding for constructing `time.Location` value ([#6219](https://github.com/pocketbase/pocketbase/discussions/6219)).
- Added `inflector.Camelize(str)` and `inflector.Singularize(str)` helper methods.
- Use the non-transactional app instance during the realtime records delete access checks to ensure that cascade deleted records with API rules relying on the parent will be resolved.
- Other minor improvements (_replaced all `bool` exists db scans with `int` for broader drivers compatibility, updated API Preview sample error responses, updated UI dependencies, etc._)
## v0.24.4
- Fixed fields extraction for view query with nested comments ([#6309](https://github.com/pocketbase/pocketbase/discussions/6309)).
- Bumped GitHub action min Go version to 1.23.5 as it comes with some [minor security fixes](https://github.com/golang/go/issues?q=milestone%3AGo1.23.5).
## v0.24.3
- Fixed incorrectly reported unique validator error for fields starting with name of another field ([#6281](https://github.com/pocketbase/pocketbase/pull/6281); thanks @svobol13).
- Reload the created/edited records data in the RecordsPicker UI.
- Updated Go dependencies.
## v0.24.2
- Fixed display fields extraction when there are multiple "Presentable" `relation` fields in a single related collection ([#6229](https://github.com/pocketbase/pocketbase/issues/6229)).
## v0.24.1
- Added missing time macros in the UI autocomplete.
- Fixed JSVM types for structs and functions with multiple generic parameters.
## v0.24.0
- ⚠️ Removed the "dry submit" when executing the collections Create API rule
(you can find more details why this change was introduced and how it could affect your app in https://github.com/pocketbase/pocketbase/discussions/6073).
For most users it should be non-breaking change, BUT if you have Create API rules that uses self-references or view counters you may have to adjust them manually.
With this change the "multi-match" operators are also normalized in case the targeted collection doesn't have any records
(_or in other words, `@collection.example.someField != "test"` will result to `true` if `example` collection has no records because it satisfies the condition that all available "example" records mustn't have `someField` equal to "test"_).
As a side-effect of all of the above minor changes, the record create API performance has been also improved ~4x times in high concurrent scenarios (500 concurrent clients inserting total of 50k records - [old (58.409064001s)](https://github.com/pocketbase/benchmarks/blob/54140be5fb0102f90034e1370c7f168fbcf0ddf0/results/hetzner_cax41_cgo.md#creating-50000-posts100k-reqs50000-conc500-rulerequestauthid----requestdatapublicisset--true) vs [new (13.580098262s)](https://github.com/pocketbase/benchmarks/blob/7df0466ac9bd62fe0a1056270d20ef82012f0234/results/hetzner_cax41_cgo.md#creating-50000-posts100k-reqs50000-conc500-rulerequestauthid----requestbodypublicisset--true)).
- ⚠️ Changed the type definition of `store.Store[T any]` to `store.Store[K comparable, T any]` to allow support for custom store key types.
For most users it should be non-breaking change, BUT if you are calling `store.New[any](nil)` instances you'll have to specify the store key type, aka. `store.New[string, any](nil)`.
- Added `@yesterday` and `@tomorrow` datetime filter macros.
- Added `:lower` filter modifier (e.g. `title:lower = "lorem"`).
- Added `mailer.Message.InlineAttachments` field for attaching inline files to an email (_aka. `cid` links_).
- Added cache for the JSVM `arrayOf(m)`, `DynamicModel`, etc. dynamic `reflect` created types.
- Added auth collection select for the settings "Send test email" popup ([#6166](https://github.com/pocketbase/pocketbase/issues/6166)).
- Added `record.SetRandomPassword()` to simplify random password generation usually used in the OAuth2 or OTP record creation flows.
_The generated ~30 chars random password is assigned directly as bcrypt hash and ignores the `password` field plain value validators like min/max length or regex pattern._
- Added option to list and trigger the registered app level cron jobs via the Web API and UI.
- Added extra validators for the collection field `int64` options (e.g. `FileField.MaxSize`) restricting them to the max safe JSON number (2^53-1).
- Added option to unset/overwrite the default PocketBase superuser installer using `ServeEvent.InstallerFunc`.
- Added `app.FindCachedCollectionReferences(collection, excludeIds)` to speedup records cascade delete almost twice for projects with many collections.
- Added `tests.NewTestAppWithConfig(config)` helper if you need more control over the test configurations like `IsDev`, the number of allowed connections, etc.
- Invalidate all record tokens when the auth record email is changed programmatically or by a superuser ([#5964](https://github.com/pocketbase/pocketbase/issues/5964)).
- Eagerly interrupt waiting for the email alert send in case it takes longer than 15s.
- Normalized the hidden fields filter checks and allow targetting hidden fields in the List API rule.
- Fixed "Unique identify fields" input not refreshing on unique indexes change ([#6184](https://github.com/pocketbase/pocketbase/issues/6184)).
## v0.23.12
- Added warning logs in case of mismatched `modernc.org/sqlite` and `modernc.org/libc` versions ([#6136](https://github.com/pocketbase/pocketbase/issues/6136#issuecomment-2556336962)).
- Skipped the default body size limit middleware for the backup upload endpoint ([#6152](https://github.com/pocketbase/pocketbase/issues/6152)).
## v0.23.11
- Upgraded `golang.org/x/net` to 0.33.0 to fix [CVE-2024-45338](https://www.cve.org/CVERecord?id=CVE-2024-45338).
_PocketBase uses the vulnerable functions primarily for the auto html->text mail generation, but most applications shouldn't be affected unless you are manually embedding unrestricted user provided value in your mail templates._
## v0.23.10
- Renew the superuser file token cache when clicking on the thumb preview or download link ([#6137](https://github.com/pocketbase/pocketbase/discussions/6137)).
- Upgraded `modernc.org/sqlite` to 1.34.3 to fix "disk io" error on arm64 systems.
_If you are extending PocketBase with Go and upgrading with `go get -u` make sure to manually set in your go.mod the `modernc.org/libc` indirect dependency to v1.55.3, aka. the exact same version the driver is using._
## v0.23.9
- Replaced `strconv.Itoa` with `strconv.FormatInt` to avoid the int64->int conversion overflow on 32-bit platforms ([#6132](https://github.com/pocketbase/pocketbase/discussions/6132)).
## v0.23.8
- Fixed Model->Record and Model->Collection hook events sync for nested and/or inner-hook transactions ([#6122](https://github.com/pocketbase/pocketbase/discussions/6122)).
- Other minor improvements (updated Go and npm deps, added extra escaping for the default mail record params in case the emails are stored as html files, fixed code comment typos, etc.).
## v0.23.7
- Fixed JSVM exception -> Go error unwrapping when throwing errors from non-request hooks ([#6102](https://github.com/pocketbase/pocketbase/discussions/6102)).
## v0.23.6
- Fixed `$filesystem.fileFromURL` documentation and generated type ([#6058](https://github.com/pocketbase/pocketbase/issues/6058)).
- Fixed `X-Forwarded-For` header typo in the suggested UI "Common trusted proxy" headers ([#6063](https://github.com/pocketbase/pocketbase/pull/6063)).
- Updated the `text` field max length validator error message to make it more clear ([#6066](https://github.com/pocketbase/pocketbase/issues/6066)).
- Other minor fixes (updated Go deps, skipped unnecessary validator check when the default primary key pattern is used, updated JSVM types, etc.).
## v0.23.5
- Fixed UI logs search not properly accounting for the "Include requests by superusers" toggle when multiple search expressions are used.
- Fixed `text` field max validation error message ([#6053](https://github.com/pocketbase/pocketbase/issues/6053)).
- Other minor fixes (comment typos, JSVM types update).
- Updated Go deps and the min Go release GitHub action version to 1.23.4.
## v0.23.4
- Fixed `autodate` fields not refreshing when calling `Save` multiple times on the same `Record` instance ([#6000](https://github.com/pocketbase/pocketbase/issues/6000)).
- Added more descriptive test OTP id and failure log message ([#5982](https://github.com/pocketbase/pocketbase/discussions/5982)).
- Moved the default UI CSP from meta tag to response header ([#5995](https://github.com/pocketbase/pocketbase/discussions/5995)).
- Updated Go and npm dependencies.
## v0.23.3
- Fixed Gzip middleware not applying when serving static files.
- Fixed `Record.Fresh()`/`Record.Clone()` methods not properly cloning `autodate` fields ([#5973](https://github.com/pocketbase/pocketbase/discussions/5973)).
## v0.23.2
- Fixed `RecordQuery()` custom struct scanning ([#5958](https://github.com/pocketbase/pocketbase/discussions/5958)).
- Fixed `--dev` log query print formatting.
- Added support for passing more than one id in the `Hook.Unbind` method for consistency with the router.
- Added collection rules change list in the confirmation popup
(_to avoid getting anoying during development, the rules confirmation currently is enabled only when using https_).
## v0.23.1
- Added `RequestEvent.Blob(status, contentType, bytes)` response write helper ([#5940](https://github.com/pocketbase/pocketbase/discussions/5940)).
- Added more descriptive error messages.
## v0.23.0
> [!NOTE]
> You don't have to upgrade to PocketBase v0.23.0 if you are not planning further developing
> your existing app and/or are satisfied with the v0.22.x features set. There are no identified critical issues
> with PocketBase v0.22.x yet and in the case of critical bugs and security vulnerabilities, the fixes
> will be backported for at least until Q1 of 2025 (_if not longer_).
>
> **If you don't plan upgrading make sure to pin the SDKs version to their latest PocketBase v0.22.x compatible:**
> - JS SDK: `<0.22.0`
> - Dart SDK: `<0.19.0`
> [!CAUTION]
> This release introduces many Go/JSVM and Web APIs breaking changes!
>
> Existing `pb_data` will be automatically upgraded with the start of the new executable,
> but custom Go or JSVM (`pb_hooks`, `pb_migrations`) and JS/Dart SDK code will have to be migrated manually.
> Please refer to the below upgrade guides:
> - Go: https://pocketbase.io/v023upgrade/go/.
> - JSVM: https://pocketbase.io/v023upgrade/jsvm/.
>
> If you had already switched to some of the earlier `<v0.23.0-rc14` versions and have generated a full collections snapshot migration (aka. `./pocketbase migrate collections`), then you may have to regenerate the migration file to ensure that it includes the latest changes.
PocketBase v0.23.0 is a major refactor of the internals with the overall goal of making PocketBase an easier to use Go framework.
There are a lot of changes but to highlight some of the most notable ones:
- New and more [detailed documentation](https://pocketbase.io/docs/).
_The old documentation could be accessed at [pocketbase.io/old](https://pocketbase.io/old/)._
- Replaced `echo` with a new router built on top of the Go 1.22 `net/http` mux enhancements.
- Merged `daos` packages in `core.App` to simplify the DB operations (_the `models` package structs are also migrated in `core`_).
- Option to specify custom `DBConnect` function as part of the app configuration to allow different `database/sql` SQLite drivers (_turso/libsql, sqlcipher, etc._) and custom builds.
_Note that we no longer loads the `mattn/go-sqlite3` driver by default when building with `CGO_ENABLED=1` to avoid `multiple definition` linker errors in case different CGO SQLite drivers or builds are used. You can find an example how to enable it back if you want to in the [new documentation](https://pocketbase.io/docs/go-overview/#github-commattngo-sqlite3)._
- New hooks allowing better control over the execution chain and error handling (_including wrapping an entire hook chain in a single DB transaction_).
- Various `Record` model improvements (_support for get/set modifiers, simplfied file upload by treating the file(s) as regular field value like `record.Set("document", file)`, etc._).
- Dedicated fields structs with safer defaults to make it easier creating/updating collections programmatically.
- Option to mark field as "Hidden", disallowing regular users to read or modify it (_there is also a dedicated Record hook to hide/unhide Record fields programmatically from a single place_).
- Option to customize the default system collection fields (`id`, `email`, `password`, etc.).
- Admins are now system `_superusers` auth records.
- Builtin rate limiter (_supports tags, wildcards and exact routes matching_).
- Batch/transactional Web API endpoint.
- Impersonate Web API endpoint (_it could be also used for generating fixed/nonrenewable superuser tokens, aka. "API keys"_).
- Support for custom user request activity log attributes.
- One-Time Password (OTP) auth method (_via email code_).
- Multi-Factor Authentication (MFA) support (_currently requires any 2 different auth methods to be used_).
- Support for Record "proxy/projection" in preparation for the planned autogeneration of typed Go record models.
- Linear OAuth2 provider ([#5909](https://github.com/pocketbase/pocketbase/pull/5909); thanks @chnfyi).
- WakaTime OAuth2 provider ([#5829](https://github.com/pocketbase/pocketbase/pull/5829); thanks @tigawanna).
- Notion OAuth2 provider ([#4999](https://github.com/pocketbase/pocketbase/pull/4999); thanks @s-li1).
- monday.com OAuth2 provider ([#5346](https://github.com/pocketbase/pocketbase/pull/5346); thanks @Jaytpa01).
- New Instagram provider compatible with the new Instagram Login APIs ([#5588](https://github.com/pocketbase/pocketbase/pull/5588); thanks @pnmcosta).
_The provider key is `instagram2` to prevent conflicts with existing linked users._
- Option to retrieve the OIDC OAuth2 user info from the `id_token` payload for the cases when the provider doesn't have a dedicated user info endpoint.
- Various minor UI improvements (_recursive `Presentable` view, slightly different collection options organization, zoom/pan for the logs chart, etc._)
- and many more...
#### Go/JSVM APIs changes
> - Go: https://pocketbase.io/v023upgrade/go/.
> - JSVM: https://pocketbase.io/v023upgrade/jsvm/.
#### SDKs changes
- [JS SDK v0.22.0](https://github.com/pocketbase/js-sdk/blob/master/CHANGELOG.md)
- [Dart SDK v0.19.0](https://github.com/pocketbase/dart-sdk/blob/master/CHANGELOG.md)
#### Web APIs changes
- New `POST /api/batch` endpoint.
- New `GET /api/collections/meta/scaffolds` endpoint.
- New `DELETE /api/collections/{collection}/truncate` endpoint.
- New `POST /api/collections/{collection}/request-otp` endpoint.
- New `POST /api/collections/{collection}/auth-with-otp` endpoint.
- New `POST /api/collections/{collection}/impersonate/{id}` endpoint.
- ⚠️ If you are constructing requests to `/api/*` routes manually remove the trailing slash (_there is no longer trailing slash removal middleware registered by default_).
- ⚠️ Removed `/api/admins/*` endpoints because admins are converted to `_superusers` auth collection records.
- ⚠️ Previously when uploading new files to a multiple `file` field, new files were automatically appended to the existing field values.
This behaviour has changed with v0.23+ and for consistency with the other multi-valued fields when uploading new files they will replace the old ones. If you want to prepend or append new files to an existing multiple `file` field value you can use the `+` prefix or suffix:
```js
"documents": [file1, file2] // => [file1_name, file2_name]
"+documents": [file1, file2] // => [file1_name, file2_name, old1_name, old2_name]
"documents+": [file1, file2] // => [old1_name, old2_name, file1_name, file2_name]
```
- ⚠️ Removed `GET /records/{id}/external-auths` and `DELETE /records/{id}/external-auths/{provider}` endpoints because this is now handled by sending list and delete requests to the `_externalAuths` collection.
- ⚠️ Changes to the app settings model fields and response (+new options such as `trustedProxy`, `rateLimits`, `batch`, etc.). The app settings Web APIs are mostly used by the Dashboard UI and rarely by the end users, but if you want to check all settings changes please refer to the [Settings Go struct](https://github.com/pocketbase/pocketbase/blob/develop/core/settings_model.go#L121).
- ⚠️ New flatten Collection model and fields structure. The Collection model Web APIs are mostly used by the Dashboard UI and rarely by the end users, but if you want to check all changes please refer to the [Collection Go struct](https://github.com/pocketbase/pocketbase/blob/develop/core/collection_model.go#L308).
- ⚠️ The top level error response `code` key was renamed to `status` for consistency with the Go APIs.
The error field key remains `code`:
```js
{
"status": 400, // <-- old: "code"
"message": "Failed to create record.",
"data": {
"title": {
"code": "validation_required",
"message": "Missing required value."
}
}
}
```
- ⚠️ New fields in the `GET /api/collections/{collection}/auth-methods` response.
_The old `authProviders`, `usernamePassword`, `emailPassword` fields are still returned in the response but are considered deprecated and will be removed in the future._
```js
{
"mfa": {
"duration": 100,
"enabled": true
},
"otp": {
"duration": 0,
"enabled": false
},
"password": {
"enabled": true,
"identityFields": ["email", "username"]
},
"oauth2": {
"enabled": true,
"providers": [{"name": "gitlab", ...}, {"name": "google", ...}]
},
// old fields...
}
```
- ⚠️ Soft-deprecated the OAuth2 auth success `meta.avatarUrl` field in favour of `meta.avatarURL`.
- Bumped the min Go version to 1.27.0 and migrated to the new `encoding/json/v2` package.
_⚠️ Please note that Go 1.27.0 retrofitted `encoding/json` to use the v2 package under the hood but unfortunately is not fully backward compatible._
_I recommend to not push blindly an update on production and to test your PocketBase application first locally to see if everything works correctly._
+2 -2
View File
@@ -326,7 +326,7 @@
- Added "tags" support for all Record and Model related event hooks.
The "tags" allow registering event handlers that will be called only on matching table name(s) or colleciton id(s)/name(s).
The "tags" allow registering event handlers that will be called only on matching table name(s) or collection id(s)/name(s).
For example:
```go
app.OnRecordBeforeCreateRequest("articles").Add(func(e *core.RecordCreateEvent) error {
@@ -840,7 +840,7 @@ Please check the individual SDK package changelog and apply the necessary change
</tr>
</table>
- All datetime stings are now returned in ISO8601 format - with _Z_ suffix and space as separator between the date and time part:
- All datetime strings are now returned in ISO8601 format - with _Z_ suffix and space as separator between the date and time part:
<table class="d-table" width="100%">
<tr>
<th>Old</th>
+117 -3
View File
@@ -2,6 +2,120 @@
> For the most recent versions, please refer to [CHANGELOG.md](./CHANGELOG.md)
---
## v0.22.54
- (_Backported from v0.40.2_) Bumped goja and its related dependencies _(regex unescaped dash error fix and base64 optimizations)_.
- (_Backported from v0.40.2_) Return an error when filter params fallback fails to json serialize and optimized params replacement to execute in a single pass.
- (_Backported from v0.40.2_) Bumped the min Go GitHub action version to 1.27.1 as it includes some [minor `database/sql` and `enconding/json/v2` bug fixes](https://github.com/golang/go/issues?q=milestone%3AGo1.27.1).
## v0.22.53
- Workaround `encoding/json` infinite recursion when used with Go 1.27 ([#7808](https://github.com/pocketbase/pocketbase/issues/7808)).
## v0.22.52
- (_Backported from v0.39.11_) Bumped `golang.org/x/*` deps and the min Go GitHub action version to 1.26.6 because it comes with some [minor bug and security fixes](https://github.com/golang/go/issues?q=milestone%3AGo1.26.6).
## 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.
_In case the userinfo data is not sufficient, some of the providers now send a separate list emails request in order to minimize eventual linking security issues caused by custom onpremise setups (e.g. Gitea/Forgejo allows skipping the email verification if an ENV variable is configured)._
- (_Backported from v0.37.4_) ⚠️ Fixed a pre-hijacking OAuth2 linking vulnerability ([#7662](https://github.com/pocketbase/pocketbase/discussions/7662)).
## v0.22.41
- (_Backported from v0.36.9_) Updated the Discord `AuthUser.Name` field to use `global_name`.
- (_Backported from v0.36.9_) Updated `modernc.org/sqlite` to v1.48.2 _(vfs and other error path related fixes)_.
- (_Backported from v0.36.9_) Bumped min Go GitHub action version to 1.26.2 because it comes with several [minor security fixes](https://github.com/golang/go/issues?q=milestone%3AGo1.26.2).
## v0.22.40
- (_Backported from v0.36.7_) Updated `modernc.org/sqlite` to v1.46.2 and SQLite 3.51.3.
_⚠️ SQLite 3.51.3 fixed a [database corruption bug](https://sqlite.org/wal.html#walresetbug) that is very unlikely to happen (with PocketBase even more so because we queue on app level all writes and explicit transactions through a single db connection), but still it is advised to upgrade._
- (_Backported from v0.36.7_) Updated other minor Go and npm deps.
_The min Go version in the go.mod of the package was also bumped to Go 1.25.0 because some of the newer dep versions require it._
## v0.22.39
- (_Backported from v0.36.6_) Bumped min Go GitHub action version to 1.26.1 because it comes with some [minor bug and security fixes](https://github.com/golang/go/issues?q=milestone%3AGo1.26.1).
## v0.22.38
- (_Backported from v0.36.0_) Bumped min Go GitHub action version to 1.25.6 because it comes with some [minor security fixes](https://github.com/golang/go/issues?q=milestone%3AGo1.25.6).
## v0.22.37
- (_Backported from v0.34.1_) - Added missing `:` char to the autocomplete regex ([#7353](https://github.com/pocketbase/pocketbase/pull/7353)).
- (_Backported from v0.34.1_) Bumped min Go GitHub action version to 1.25.5 because it comes with some [minor security fixes](https://github.com/golang/go/issues?q=milestone%3AGo1.25.5).
_The runner action was also updated to `actions/setup-go@v6` since the previous v5 Go source seems [no longer accessible](https://github.com/actions/setup-go/pull/665#issuecomment-3416693714)._
## v0.22.36
- (_Backported from v0.30.2_) Bumped min Go GitHub action version to 1.24.8 since it comes with some [minor security fixes](https://github.com/golang/go/issues?q=milestone%3AGo1.24.8+label%3ACherryPickApproved).
@@ -67,7 +181,7 @@
- Refresh the old collections state in the Import UI after successful import submission ([#5861](https://github.com/pocketbase/pocketbase/issues/5861)).
- Added randomized throttle on failed filter list requests as a very rudimentary measure since some security researches raised concern regarding the possibity of eventual side-channel attacks.
- Added randomized throttle on failed filter list requests as a very rudimentary measure since some security researches raised concern regarding the possibility of eventual side-channel attacks.
## v0.22.24
@@ -469,7 +583,7 @@
A negative or zero value means no tests timeout.
If a single API test takes more than 3s to complete it will have a log message visible when the test fails or when `go test -v` flag is used.
- Added timestamp at the beginning of the generated JSVM types file to avoid creating it everytime with the app startup.
- Added timestamp at the beginning of the generated JSVM types file to avoid creating it every time with the app startup.
## v0.20.0
@@ -849,7 +963,7 @@
- ⚠️ Deprecated `RelationOptions.DisplayFields` in favor of the new `SchemaField.Presentable` option to avoid the duplication when a single collection is referenced more than once and/or by multiple other collections.
- ⚠️ Fill the `LastVerificationSentAt` and `LastResetSentAt` fields only after a successfull email send ([#3121](https://github.com/pocketbase/pocketbase/issues/3121)).
- ⚠️ Fill the `LastVerificationSentAt` and `LastResetSentAt` fields only after a successful email send ([#3121](https://github.com/pocketbase/pocketbase/issues/3121)).
- ⚠️ Skip API `fields` json transformations for non 20x responses ([#3176](https://github.com/pocketbase/pocketbase/issues/3176)).
+1243
View File
File diff suppressed because it is too large Load Diff
+16 -13
View File
@@ -1,17 +1,20 @@
# Contributing to PocketBase
Thanks for taking the time to improve PocketBase!
> [!IMPORTANT]
> Due to recent LLM spam, PRs are temporary disabled and only existing collaborators can open a PR.
> If you stumble on a problem that you want to fix, please consider instead opening an issue or discussion with link to your fork _(if not obvious - LLM contributions are not welcome)_.
> This status may change in the future in case GitHub finally decide to do something about the constant spam, or when I find time to move the project somewhere else.
This document describes how to prepare a PR for a change in the main repository.
- [Prerequisites](#prerequisites)
- [Making changes in the Go code](#making-changes-in-the-go-code)
- [Making changes in the Admin UI](#making-changes-in-the-admin-ui)
- [Making changes in the Superuser UI](#making-changes-in-the-admin-ui)
## Prerequisites
- Go 1.23+ (for making changes in the Go code)
- Node 18+ (for making changes in the Admin UI)
- Go 1.27+ (for making changes in the Go code)
- Node 24+ (for making changes in the Superuser UI)
If you haven't already, you can fork the main repository and clone your fork so that you can work locally:
@@ -34,7 +37,7 @@ So, let's assume that you already done some changes in the PocketBase Go code an
1. Navigate to `examples/base`
2. Run `go run main.go serve`
This will start a web server on `http://localhost:8090` with the embedded prebuilt Admin UI from `ui/dist`. And that's it!
This will start a web server on `http://localhost:8090` with the embedded prebuilt Superuser UI from `ui/dist`. And that's it!
**Before making a PR to the main repository, it is a good idea to:**
@@ -57,11 +60,11 @@ This will start a web server on `http://localhost:8090` with the embedded prebui
make lint
```
## Making changes in the Admin UI
## Making changes in the Superuser UI
PocketBase Admin UI is a single-page application (SPA) built with Svelte and Vite.
PocketBase Superuser UI is a single-page application (SPA) built with Svelte and Vite.
To start the Admin UI:
To start the Superuser UI:
1. Navigate to the `ui` project directory
2. Run `npm install` to install the node dependencies
@@ -70,13 +73,13 @@ To start the Admin UI:
npm run dev
```
You could open the browser and access the running Admin UI at `http://localhost:3000`.
You could open the browser and access the running Superuser UI at `http://localhost:5173`.
Since the Admin UI is just a client-side application, you need to have the PocketBase backend server also running in the background (either manually running the `examples/base/main.go` or download a prebuilt executable).
Since the Superuser UI is just a client-side application, you need to have the PocketBase backend server also running in the background (either manually running the `examples/base/main.go` or download a prebuilt executable).
> [!NOTE]
> By default, the Admin UI is expecting the backend server to be started at `http://localhost:8090`, but you could change that by creating a new `ui/.env.development.local` file with `PB_BACKEND_URL = YOUR_ADDRESS` variable inside it.
> By default, the Superuser UI is expecting the backend server to be started at `http://localhost:8090`, but you could change that by creating a new `ui/.env.development.local` file with `PB_BACKEND_URL = YOUR_ADDRESS` variable inside it.
Every change you make in the Admin UI should be automatically reflected in the browser at `http://localhost:3000` without reloading the page.
Every change you make in the Superuser UI should be automatically reflected in the browser at `http://localhost:5173` without reloading the page.
Once you are done with your changes, you have to build the Admin UI with `npm run build`, so that it can be embedded in the go package. And that's it - you can make your PR to the main PocketBase repository.
Once you are done with your changes, you have to build the Superuser UI with `npm run build`, so that it can be embedded in the go package. And that's it - you can make your PR to the main PocketBase repository.
+34 -24
View File
@@ -1,6 +1,6 @@
<p align="center">
<a href="https://pocketbase.io" target="_blank" rel="noopener">
<img src="https://i.imgur.com/5qimnm5.png" alt="PocketBase - open source backend in 1 file" />
<img src="https://i.imgur.com/aCBbjKx.png" alt="PocketBase - open source backend in 1 file" />
</a>
</p>
@@ -49,7 +49,7 @@ your own custom app specific business logic and still have a single portable exe
Here is a minimal example:
0. [Install Go 1.23+](https://go.dev/doc/install) (_if you haven't already_)
0. [Install Go 1.27+](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
@@ -92,30 +92,37 @@ _For more details please refer to [Extend with Go](https://pocketbase.io/docs/go
To build the minimal standalone executable, like the prebuilt ones in the releases page, you can simply run `go build` inside the `examples/base` directory:
0. [Install Go 1.23+](https://go.dev/doc/install) (_if you haven't already_)
0. [Install Go 1.27+](https://go.dev/doc/install) (_if you haven't already_)
1. Clone/download the repo
2. Navigate to `examples/base`
3. Run `GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build`
(_https://go.dev/doc/install/source#environment_)
3. Run `CGO_ENABLED=0 go build` to build a binary for your current environment
_(or to target other platforms use `GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build`; see https://go.dev/doc/install/source#environment)_
4. Start the created executable by running `./base serve`.
Note that the supported build targets by the pure Go SQLite driver at the moment are:
```
darwin amd64
darwin arm64
freebsd amd64
freebsd arm64
linux 386
linux amd64
linux arm
linux arm64
linux ppc64le
linux riscv64
linux s390x
windows amd64
windows arm64
```
| GOOS | GOARCH |
|---------|---------|
| darwin | amd64 |
| darwin | arm64 |
| freebsd | 386 |
| freebsd | amd64 |
| freebsd | arm |
| freebsd | arm64 |
| linux | 386 |
| linux | amd64 |
| linux | arm |
| linux | arm64 |
| linux | loong64 |
| linux | ppc64le |
| linux | riscv64 |
| linux | s390x |
| netbsd | amd64 |
| openbsd | amd64 |
| openbsd | arm64 |
| windows | 386 |
| windows | amd64 |
| windows | arm64 |
### Testing
@@ -132,7 +139,7 @@ Check also the [Testing guide](http://pocketbase.io/docs/testing) to learn how t
If you discover a security vulnerability within PocketBase, please send an e-mail to **support at pocketbase.io**.
All reports will be promptly addressed and you'll be credited in the fix release notes.
You could find more details in the project [Security policy](https://github.com/pocketbase/pocketbase/security/policy).
## Contributing
@@ -144,10 +151,13 @@ You could help continuing its development by:
- [Contribute to the source code](CONTRIBUTING.md)
- [Suggest new features and report issues](https://github.com/pocketbase/pocketbase/issues)
PRs for new OAuth2 providers, bug fixes, code optimizations and documentation improvements are more than welcome.
But please refrain creating PRs for _new features_ without previously discussing the implementation details.
Please refrain creating PRs for _new features_ without previously discussing the implementation details.
PocketBase has a [roadmap](https://github.com/orgs/pocketbase/projects/2) and I try to work on issues in specific order and such PRs often come in out of nowhere and skew all initial planning with tedious back-and-forth communication.
Don't get upset if I close your PR, even if it is well executed and tested. This doesn't mean that it will never be merged.
Later we can always refer to it and/or take pieces of your implementation when the time comes to work on the issue (don't worry you'll be credited in the release notes).
> [!IMPORTANT]
> Due to recent LLM spam, PRs are temporary disabled and only existing collaborators can open a PR.
> If you stumble on a problem that you want to fix, please consider instead opening an issue or discussion with link to your fork _(if not obvious - LLM contributions are not welcome)_.
> This status may change in the future in case GitHub finally decide to do something about the constant spam, or when I find time to move the project somewhere else.
+7 -2
View File
@@ -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")
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"net/http"
"regexp"
validation "github.com/go-ozzo/ozzo-validation/v4"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core"
)
+52
View File
@@ -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 {
+1 -1
View File
@@ -3,7 +3,7 @@ package apis
import (
"net/http"
validation "github.com/go-ozzo/ozzo-validation/v4"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/core/validators"
"github.com/pocketbase/pocketbase/tools/filesystem"
+9 -3
View File
@@ -15,7 +15,7 @@ import (
// StaticWildcardParam is the name of Static handler wildcard parameter.
const StaticWildcardParam = "path"
// NewRouter returns a new router instance loaded with the default app middlewares and api routes.
// NewRouter returns a new router instance loaded with the default app middlewares and routes.
func NewRouter(app core.App) (*router.Router[*core.RequestEvent], error) {
pbRouter := router.NewRouter(func(w http.ResponseWriter, r *http.Request) (*core.RequestEvent, router.EventCleanupFunc) {
event := new(core.RequestEvent)
@@ -31,9 +31,11 @@ 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))
// API routes
apiGroup := pbRouter.Group("/api")
bindSettingsApi(app, apiGroup)
bindCollectionApi(app, apiGroup)
@@ -46,6 +48,10 @@ 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)
return pbRouter, nil
}
@@ -86,7 +92,7 @@ func MustSubFS(fsys fs.FS, dir string) fs.FS {
// Static is a handler function to serve static directory content from fsys.
//
// If a file resource is missing and indexFallback is set, the request
// If a file resource is missing and indexFallback is true, the request
// will be forwarded to the base index.html (useful for SPA with pretty urls).
//
// NB! Expects the route to have a "{path...}" wildcard parameter.
@@ -94,7 +100,7 @@ func MustSubFS(fsys fs.FS, dir string) fs.FS {
// Special redirects:
// - if "path" is a file that ends in index.html, it is redirected to its non-index.html version (eg. /test/index.html -> /test/)
// - if "path" is a directory that has index.html, the index.html file is rendered,
// otherwise if missing - returns 404 or fallback to the root index.html if indexFallback is set
// otherwise if missing - returns 404 or fallback to the root index.html if indexFallback is true
//
// Example:
//
+7 -5
View File
@@ -2,7 +2,7 @@ package apis
import (
"bytes"
"encoding/json"
"encoding/json/v2"
"errors"
"io"
"mime/multipart"
@@ -14,10 +14,11 @@ import (
"strings"
"time"
validation "github.com/go-ozzo/ozzo-validation/v4"
validation "github.com/pocketbase/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/routine"
"github.com/pocketbase/pocketbase/tools/types"
"github.com/spf13/cast"
)
@@ -88,7 +89,7 @@ func (brs batchRequestsForm) validate() error {
}
// NB! When the request is submitted as multipart/form-data,
// the regular fields data is expected to be submitted as serailized
// the regular fields data is expected to be submitted as serialized
// json under the @jsonPayload field and file keys need to follow the
// pattern "requests.N.fileField" or requests[N].fileField.
func batchTransaction(e *core.RequestEvent) error {
@@ -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:
@@ -364,6 +365,7 @@ func processInternalRequest(
// assign request
event.Request = r
event.Request.Body = &router.RereadableReadCloser{ReadCloser: r.Body} // enables multiple reads
defer event.Request.Body.Close()
// assign response
rec := httptest.NewRecorder()
+65 -1
View File
@@ -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,
+88 -1
View File
@@ -3,10 +3,12 @@ package apis
import (
"errors"
"net/http"
"slices"
"strings"
validation "github.com/go-ozzo/ozzo-validation/v4"
validation "github.com/pocketbase/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"
@@ -23,6 +25,10 @@ func bindCollectionApi(app core.App, rg *router.RouterGroup[*core.RequestEvent])
subGroup.DELETE("/{collection}/truncate", collectionTruncate)
subGroup.PUT("/import", collectionsImport)
subGroup.GET("/meta/scaffolds", collectionScaffolds)
// @todo experimental
subGroup.GET("/meta/oauth2-providers", collectionListOAuth2Providers)
subGroup.POST("/meta/dry-run-view", collectionDryRunView)
}
func collectionsList(e *core.RequestEvent) error {
@@ -207,3 +213,84 @@ func collectionScaffolds(e *core.RequestEvent) error {
return e.JSON(http.StatusOK, collections)
}
type providerListItem struct {
order int
Name string `json:"name"`
DisplayName string `json:"displayName"`
Logo string `json:"logo"`
}
func collectionListOAuth2Providers(e *core.RequestEvent) error {
providers := make([]*providerListItem, 0, len(auth.Providers))
for name, factory := range auth.Providers {
p := factory()
providers = append(providers, &providerListItem{
order: p.Order(),
Name: name,
DisplayName: p.DisplayName(),
Logo: p.Logo(),
})
}
slices.SortStableFunc(providers, func(a, b *providerListItem) int {
// sort by order
if a.order < b.order {
return -1
}
if a.order > b.order {
return 1
}
// fallback sort by name
if a.Name < b.Name {
return -1
}
if a.Name > b.Name {
return 1
}
return 0
})
return e.JSON(http.StatusOK, providers)
}
func collectionDryRunView(e *core.RequestEvent) error {
// extra precaution in case reused in custom route group
if !e.HasSuperuserAuth() {
return e.ForbiddenError("", nil)
}
form := dryRunViewForm{}
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 := e.App.DryRunView(form.Query, 10)
if err != nil {
return firstApiError(err, e.BadRequestError("Invalid view query. Raw error: \n"+err.Error(), nil))
}
return e.JSON(http.StatusOK, result)
}
type dryRunViewForm struct {
Query string `form:"query" json:"query"`
}
func (form *dryRunViewForm) validate() error {
return validation.ValidateStruct(form,
validation.Field(&form.Query, validation.Required, validation.Length(0, 5000)),
)
}
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"errors"
"net/http"
validation "github.com/go-ozzo/ozzo-validation/v4"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core"
)
+255 -6
View File
@@ -536,7 +536,7 @@ func TestCollectionCreate(t *testing.T) {
`"type":"base"`,
`"system":false`,
// ensures that id field was prepended
`"fields":[{"autogeneratePattern":"[a-z0-9]{15}","hidden":false,"id":"text3208210256","max":15,"min":15,"name":"id","pattern":"^[a-z0-9]+$","presentable":false,"primaryKey":true,"required":true,"system":true,"type":"text"},{"autogeneratePattern":"","hidden":false,"id":"12345789","max":0,"min":0,"name":"test","pattern":"","presentable":false,"primaryKey":false,"required":false,"system":false,"type":"text"}]`,
`"fields":[{"autogeneratePattern":"[a-z0-9]{15}","help":"","hidden":false,"id":"text3208210256","max":15,"min":15,"name":"id","pattern":"^[a-z0-9]+$","presentable":false,"primaryKey":true,"required":true,"system":true,"type":"text"},{"autogeneratePattern":"","help":"","hidden":false,"id":"12345789","max":0,"min":0,"name":"test","pattern":"","presentable":false,"primaryKey":false,"required":false,"system":false,"type":"text"}]`,
},
ExpectedEvents: map[string]int{
"*": 0,
@@ -585,7 +585,7 @@ func TestCollectionCreate(t *testing.T) {
`"name":"verified"`,
`"duration":123`,
// should overwrite the user required option but keep the min value
`{"autogeneratePattern":"","hidden":true,"id":"text2504183744","max":0,"min":10,"name":"tokenKey","pattern":"","presentable":false,"primaryKey":false,"required":true,"system":true,"type":"text"}`,
`{"autogeneratePattern":"","help":"","hidden":true,"id":"text2504183744","max":0,"min":10,"name":"tokenKey","pattern":"","presentable":false,"primaryKey":false,"required":true,"system":true,"type":"text"}`,
},
NotExpectedContent: []string{
`"secret":"`,
@@ -751,7 +751,7 @@ func TestCollectionCreate(t *testing.T) {
"name":"new",
"type":"view",
"fields":[{"type":"text","id":"12345789","name":"ignored!@#$"}],
"viewQuery":"invalid"
"viewQuery":"select '123' as abc"
}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
@@ -780,7 +780,7 @@ func TestCollectionCreate(t *testing.T) {
"name":"new",
"type":"view",
"fields":[{"type":"text","id":"12345789","name":"ignored!@#$"}],
"viewQuery": "select 1 as id from ` + core.CollectionNameSuperusers + `"
"viewQuery": "select 1 as id from ` + core.CollectionNameSuperusers + ` limit 1"
}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
@@ -789,7 +789,7 @@ func TestCollectionCreate(t *testing.T) {
ExpectedContent: []string{
`"name":"new"`,
`"type":"view"`,
`"fields":[{"autogeneratePattern":"","hidden":false,"id":"text3208210256","max":0,"min":0,"name":"id","pattern":"^[a-z0-9]+$","presentable":false,"primaryKey":true,"required":true,"system":true,"type":"text"}]`,
`"fields":[{"autogeneratePattern":"","help":"","hidden":false,"id":"text3208210256","max":0,"min":0,"name":"id","pattern":"^[a-z0-9]+$","presentable":false,"primaryKey":true,"required":true,"system":true,"type":"text"}]`,
},
ExpectedEvents: map[string]int{
"*": 0,
@@ -1225,6 +1225,71 @@ func TestCollectionUpdate(t *testing.T) {
"OnModelValidate": 1,
},
},
{
Name: "add another OAuth2 provider to an auth collection",
Method: http.MethodPatch,
URL: "/api/collections/users",
Body: strings.NewReader(`{
"oauth2": {
"providers": [
{"name": "apple", "clientId": "a", "clientSecret": "b"},
{
"pkce": null,
"name": "google",
"authURL": "",
"displayName": "existing",
"extra": {}
}
]
}
}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
// verify that the collection has google and gitlab as OAuth2 providers
users, err := app.FindCollectionByNameOrId("users")
if err != nil {
t.Fatal(err)
}
if v := len(users.OAuth2.Providers); v != 2 {
t.Fatalf("Expected 2 OAuth2 providers, got %d", v)
}
if v := users.OAuth2.Providers[0].Name; v != "gitlab" {
t.Fatalf("Expected provider 0 to be %s, got %s", "gitlab", v)
}
if v := users.OAuth2.Providers[1].Name; v != "google" {
t.Fatalf("Expected provider 1 to be %s, got %s", "google", v)
}
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"name":"google"`,
`"name":"apple"`,
`"displayName":"existing"`,
`"clientId":"test"`,
`"clientId":"a"`,
},
NotExpectedContent: []string{
`"name":"gitlab"`,
`clientSecret`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnCollectionUpdateRequest": 1,
"OnCollectionUpdate": 1,
"OnCollectionUpdateExecute": 1,
"OnCollectionAfterUpdateSuccess": 1,
"OnCollectionValidate": 1,
"OnModelUpdate": 1,
"OnModelUpdateExecute": 1,
"OnModelAfterUpdateSuccess": 1,
"OnModelValidate": 1,
},
},
// view
// -----------------------------------------------------------
@@ -1262,7 +1327,7 @@ func TestCollectionUpdate(t *testing.T) {
Body: strings.NewReader(`{
"name":"view2_update",
"fields":[{"type":"text","id":"12345789","name":"ignored!@#$"}],
"viewQuery": "select 2 as id, created, updated, email from ` + core.CollectionNameSuperusers + `"
"viewQuery": "select 2 as id, created, updated, email from ` + core.CollectionNameSuperusers + ` limit 1"
}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
@@ -1584,3 +1649,187 @@ func TestCollectionTruncate(t *testing.T) {
scenario.Test(t)
}
}
func TestCollectionOAuth2Providers(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "unauthorized",
Method: http.MethodGet,
URL: "/api/collections/meta/oauth2-providers",
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as regular user",
Method: http.MethodGet,
URL: "/api/collections/meta/oauth2-providers",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as superuser",
Method: http.MethodGet,
URL: "/api/collections/meta/oauth2-providers",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`{"name":"oidc3","displayName":"OIDC","logo":"<svg`,
},
NotExpectedContent: []string{
`"order":`,
`"pkce":`,
`"scopes":`,
`"authURL":`,
`"tokenURL":`,
`"userInfoURL":`,
},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestCollectionTestView(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "unauthorized",
Method: http.MethodPost,
URL: "/api/collections/meta/dry-run-view",
Body: strings.NewReader(`{"query":"select 1 as id"}`),
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as regular user",
Method: http.MethodPost,
URL: "/api/collections/meta/dry-run-view",
Body: strings.NewReader(`{"query":"select 1 as id"}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as superuser",
Method: http.MethodPost,
URL: "/api/collections/meta/dry-run-view",
Body: strings.NewReader(`{"query":"select 1 as id"}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"fields":[{`,
`"name":"id"`,
`"type":"text"`,
`"sample":[{`,
`"id":"1"`,
},
},
{
Name: "empty query",
Method: http.MethodPost,
URL: "/api/collections/meta/dry-run-view",
Body: strings.NewReader(`{"query":""}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{"query":`,
},
},
{
Name: "query length beyond validator limit",
Method: http.MethodPost,
URL: "/api/collections/meta/dry-run-view",
Body: strings.NewReader(`{"query":"` + strings.Repeat("a", 5001) + `"}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{"query":`,
},
},
{
Name: "query with length equal to the validator limit",
Method: http.MethodPost,
URL: "/api/collections/meta/dry-run-view",
Body: strings.NewReader(`{"query":"select 1 as id` + strings.Repeat(" ", 4986) + `"}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"fields":[{`,
`"name":"id"`,
`"type":"text"`,
`"sample":[`,
`"id":"1"`,
},
},
{
Name: "missing ids sample",
Method: http.MethodPost,
URL: "/api/collections/meta/dry-run-view",
Body: strings.NewReader(`{"query":"(select 1 as id union select '' as id)"}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{}`,
`Raw error:`,
},
},
{
Name: "duplicated ids sample",
Method: http.MethodPost,
URL: "/api/collections/meta/dry-run-view",
Body: strings.NewReader(`{"query":"(select 1 as id union all select 1 as id)"}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{}`,
`Raw error:`,
},
},
{
Name: "write query",
Method: http.MethodPost,
URL: "/api/collections/meta/dry-run-view",
Body: strings.NewReader(`{"query":"CREATE TABLE t1(x INT)"}`),
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{}`,
`Raw error:`,
},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
+3 -4
View File
@@ -77,10 +77,13 @@ func TestCronsRun(t *testing.T) {
app.Cron().Add("test", "* * * * *", func() {
app.Store().Set("testJobCalls", cast.ToInt(app.Store().Get("testJobCalls"))+1)
})
app.Cron().Stop()
}
expectedCalls := func(expected int) func(t testing.TB, app *tests.TestApp, res *http.Response) {
return func(t testing.TB, app *tests.TestApp, res *http.Response) {
time.Sleep(50 * time.Millisecond)
total := cast.ToInt(app.Store().Get("testJobCalls"))
if total != expected {
t.Fatalf("Expected total testJobCalls %d, got %d", expected, total)
@@ -93,7 +96,6 @@ func TestCronsRun(t *testing.T) {
Name: "unauthorized",
Method: http.MethodPost,
URL: "/api/crons/test",
Delay: 50 * time.Millisecond,
BeforeTestFunc: beforeTestFunc,
AfterTestFunc: expectedCalls(0),
ExpectedStatus: 401,
@@ -107,7 +109,6 @@ func TestCronsRun(t *testing.T) {
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
Delay: 50 * time.Millisecond,
BeforeTestFunc: beforeTestFunc,
AfterTestFunc: expectedCalls(0),
ExpectedStatus: 403,
@@ -121,7 +122,6 @@ func TestCronsRun(t *testing.T) {
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
Delay: 50 * time.Millisecond,
BeforeTestFunc: beforeTestFunc,
AfterTestFunc: expectedCalls(0),
ExpectedStatus: 404,
@@ -135,7 +135,6 @@ func TestCronsRun(t *testing.T) {
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
Delay: 50 * time.Millisecond,
BeforeTestFunc: beforeTestFunc,
AfterTestFunc: expectedCalls(1),
ExpectedStatus: 204,
+95
View File
@@ -0,0 +1,95 @@
package apis
import (
"bytes"
"errors"
"fmt"
"io"
"log/slog"
"os"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/ui"
)
// bindUIExtensions binds the superuser UI extensions routes to the ServeEvent.Router.
//
// This method does nothing if the superuser UI is not bundled (aka. build with "no_ui" tag),
func bindUIExtensions(app core.App) {
if ui.DistDirFS == nil {
return
}
app.OnServe().Bind(&hook.Handler[*core.ServeEvent]{
Priority: 9999, // execute as latest as possible
Func: func(se *core.ServeEvent) error {
uiGroup := se.Router.Group("/_").
BindFunc(func(e *core.RequestEvent) error {
if !e.App.IsDev() && e.Response.Header().Get("Cache-Control") == "" {
e.Response.Header().Set("Cache-Control", "max-age=1209600, stale-while-revalidate=86400")
}
if e.Response.Header().Get("Content-Security-Policy") == "" {
e.Response.Header().Set("Content-Security-Policy", defaultCSP)
}
return e.Next()
}).
Bind(Gzip())
// register static extension routes
for _, ext := range se.UIExtensions {
if ext.Name == "" || ext.FS == nil {
se.App.Logger().Debug("Invalid UI extension configuration", slog.Any("extension", ext))
continue
}
uiGroup.GET("/extensions/"+ext.Name+"/{path...}", Static(ext.FS, false))
}
// combine all extensions main.js in one file
//
// note: don't cache in memory to allow previewing changes without restart
uiGroup.GET("/extensions.js", func(re *core.RequestEvent) error {
buf := new(bytes.Buffer)
for _, ext := range se.UIExtensions {
err := copyExtensionMainjs(buf, ext)
if err != nil {
return re.InternalServerError("An error occurred while generating the main.js extension file", err)
}
}
return re.Stream(200, "text/javascript", buf)
}).Bind(SkipSuccessActivityLog())
return se.Next()
},
})
}
func copyExtensionMainjs(buf *bytes.Buffer, ext core.UIExtension) error {
f, err := ext.FS.Open("main.js")
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil // nothing to copy
}
return fmt.Errorf("[UI extension %q] main.js open error: %w", ext.Name, err)
}
defer f.Close()
// wrap in a self-executing function to avoid scope and concatenation issues
// (the await/async is for top-level await)
_, _ = buf.WriteString("await (async function(){")
_, err = io.Copy(buf, f)
if err != nil {
return fmt.Errorf("[UI extension %q] main.js copy error: %w", ext.Name, err)
}
_, _ = buf.WriteString("})();")
return nil
}
+177
View File
@@ -0,0 +1,177 @@
package apis_test
import (
"net/http"
"testing"
"testing/fstest"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/ui"
)
// note: don't run in parallel to avoid conflicts with the ui.DistDirFS nil test
func TestUIExtensions_Mainjs(t *testing.T) {
successAfterTestFunc := func(t testing.TB, app *tests.TestApp, res *http.Response) {
expected := "text/javascript"
if ct := res.Header.Get("content-type"); ct != expected {
t.Fatalf("Expected response Content-Type %q, got %q", expected, ct)
}
}
oldDistDirFS := ui.DistDirFS
scenarios := []tests.ApiScenario{
{
Name: "disabled UI",
Method: http.MethodGet,
URL: "/_/extensions.js",
TestAppFactory: func(t testing.TB) *tests.TestApp {
app, err := tests.NewTestApp()
if err != nil {
t.Fatal(err)
}
// simulate no_ui tag (needs to be cleared before the router is initialized)
ui.DistDirFS = nil
return app
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
ui.DistDirFS = oldDistDirFS
},
ExpectedStatus: 404,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "no extensions",
Method: http.MethodGet,
URL: "/_/extensions.js",
AfterTestFunc: successAfterTestFunc,
ExpectedStatus: 200,
ExpectedContent: []string{},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "with extensions",
Method: http.MethodGet,
URL: "/_/extensions.js",
TestAppFactory: func(t testing.TB) *tests.TestApp {
app, err := tests.NewTestApp()
if err != nil {
t.Fatal(err)
}
app.OnServe().BindFunc(func(e *core.ServeEvent) error {
e.UIExtensions = createTestExtensions()
return e.Next()
})
return app
},
AfterTestFunc: successAfterTestFunc,
ExpectedStatus: 200,
ExpectedContent: []string{"await (async function(){ext1_main})();await (async function(){ext3_main})();"},
ExpectedEvents: map[string]int{"*": 0},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
// note: don't run in parallel to avoid conflicts with the ui.DistDirFS nil test
func TestUIExtensions_Files(t *testing.T) {
testAppFactory := func(t testing.TB) *tests.TestApp {
app, err := tests.NewTestApp()
if err != nil {
t.Fatal(err)
}
app.OnServe().BindFunc(func(e *core.ServeEvent) error {
e.UIExtensions = createTestExtensions()
return e.Next()
})
return app
}
scenarios := []tests.ApiScenario{
{
Name: "no extensions",
Method: http.MethodGet,
URL: "/_/extensions/ext1/test.txt",
ExpectedStatus: 404,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "with missing extension file",
Method: http.MethodGet,
URL: "/_/extensions/ext1/missing",
TestAppFactory: testAppFactory,
ExpectedStatus: 404,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "with existing extension file (ext1)",
Method: http.MethodGet,
URL: "/_/extensions/ext1/test.txt",
TestAppFactory: testAppFactory,
ExpectedStatus: 200,
ExpectedContent: []string{"ext1_txt"},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "with existing extension file (extension name escape)",
Method: http.MethodGet,
URL: "/_/extensions/ext3%20with%20spaces/test.txt",
TestAppFactory: testAppFactory,
ExpectedStatus: 200,
ExpectedContent: []string{"ext3_txt"},
ExpectedEvents: map[string]int{"*": 0},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func createTestExtensions() []core.UIExtension {
return []core.UIExtension{
{
Name: "ext1",
FS: fstest.MapFS{
"main.js": &fstest.MapFile{
Data: []byte("ext1_main"),
},
"test.txt": &fstest.MapFile{
Data: []byte("ext1_txt"),
},
},
},
{
Name: "ext2",
FS: fstest.MapFS{
"test.txt": &fstest.MapFile{
Data: []byte("ext2_txt"),
},
},
},
{
Name: "ext3 with spaces",
FS: fstest.MapFS{
"main.js": &fstest.MapFile{
Data: []byte("ext3_main"),
},
"test.txt": &fstest.MapFile{
Data: []byte("ext3_txt"),
},
},
},
}
}
+30 -17
View File
@@ -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
@@ -142,8 +152,14 @@ func (api *fileApi) download(e *core.RequestEvent) error {
defer fsys.Close()
originalPath := baseFilesPath + "/" + filename
servedPath := originalPath
servedName := filename
event := new(core.FileDownloadRequestEvent)
event.RequestEvent = e
event.Collection = collection
event.Record = record
event.FileField = fileField
event.ServedPath = originalPath
event.ServedName = filename
// check for valid thumb size param
thumbSize := e.Request.URL.Query().Get("thumb")
@@ -157,34 +173,31 @@ func (api *fileApi) download(e *core.RequestEvent) error {
// check if it is an image
if list.ExistInSlice(oAttrs.ContentType, imageContentTypes) {
// add thumb size as file suffix
servedName = thumbSize + "_" + filename
servedPath = baseFilesPath + "/thumbs_" + filename + "/" + servedName
event.ServedName = thumbSize + "_" + filename
event.ServedPath = baseFilesPath + "/thumbs_" + filename + "/" + event.ServedName
// create a new thumb if it doesn't exist
if exists, _ := fsys.Exists(servedPath); !exists {
if err := api.createThumb(e, fsys, originalPath, servedPath, thumbSize); err != nil {
if exists, _ := fsys.Exists(event.ServedPath); !exists {
if err := api.createThumb(e, fsys, originalPath, event.ServedPath, thumbSize); err != nil {
e.App.Logger().Warn(
"Fallback to original - failed to create thumb "+servedName,
"Fallback to original - failed to create thumb "+event.ServedName,
slog.Any("error", err),
slog.String("original", originalPath),
slog.String("thumb", servedPath),
slog.String("thumb", event.ServedPath),
)
// fallback to the original
servedName = filename
servedPath = originalPath
event.ThumbError = err
event.ServedName = filename
event.ServedPath = originalPath
}
}
}
}
event := new(core.FileDownloadRequestEvent)
event.RequestEvent = e
event.Collection = collection
event.Record = record
event.FileField = fileField
event.ServedPath = servedPath
event.ServedName = servedName
if thumbSize != "" && event.ThumbError == nil && event.ServedPath == originalPath {
event.ThumbError = fmt.Errorf("the thumb size %q or the original file format are not supported", thumbSize)
}
// clickjacking shouldn't be a concern when serving uploaded files,
// so it safe to unset the global X-Frame-Options to allow files embedding
+132 -24
View File
@@ -181,9 +181,17 @@ func TestFileDownload(t *testing.T) {
},
},
{
Name: "existing image - missing thumb (should fallback to the original)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=999x999",
Name: "existing image - missing thumb (should fallback to the original)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=999x999",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnFileDownloadRequest().BindFunc(func(e *core.FileDownloadRequestEvent) error {
if e.ThumbError == nil {
t.Fatal("Expected thumb error, got nil")
}
return e.Next()
})
},
ExpectedStatus: 200,
ExpectedContent: []string{string(testImg)},
ExpectedEvents: map[string]int{
@@ -192,9 +200,17 @@ func TestFileDownload(t *testing.T) {
},
},
{
Name: "existing image - existing thumb (crop center)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=70x50",
Name: "existing image - existing thumb (crop center)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=70x50",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnFileDownloadRequest().BindFunc(func(e *core.FileDownloadRequestEvent) error {
if e.ThumbError != nil {
t.Fatalf("Expected no thumb error, got %v", e.ThumbError)
}
return e.Next()
})
},
ExpectedStatus: 200,
ExpectedContent: []string{string(testThumbCropCenter)},
ExpectedEvents: map[string]int{
@@ -203,9 +219,17 @@ func TestFileDownload(t *testing.T) {
},
},
{
Name: "existing image - existing thumb (crop top)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=70x50t",
Name: "existing image - existing thumb (crop top)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=70x50t",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnFileDownloadRequest().BindFunc(func(e *core.FileDownloadRequestEvent) error {
if e.ThumbError != nil {
t.Fatalf("Expected no thumb error, got %v", e.ThumbError)
}
return e.Next()
})
},
ExpectedStatus: 200,
ExpectedContent: []string{string(testThumbCropTop)},
ExpectedEvents: map[string]int{
@@ -214,9 +238,17 @@ func TestFileDownload(t *testing.T) {
},
},
{
Name: "existing image - existing thumb (crop bottom)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=70x50b",
Name: "existing image - existing thumb (crop bottom)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=70x50b",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnFileDownloadRequest().BindFunc(func(e *core.FileDownloadRequestEvent) error {
if e.ThumbError != nil {
t.Fatalf("Expected no thumb error, got %v", e.ThumbError)
}
return e.Next()
})
},
ExpectedStatus: 200,
ExpectedContent: []string{string(testThumbCropBottom)},
ExpectedEvents: map[string]int{
@@ -225,9 +257,17 @@ func TestFileDownload(t *testing.T) {
},
},
{
Name: "existing image - existing thumb (fit)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=70x50f",
Name: "existing image - existing thumb (fit)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=70x50f",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnFileDownloadRequest().BindFunc(func(e *core.FileDownloadRequestEvent) error {
if e.ThumbError != nil {
t.Fatalf("Expected no thumb error, got %v", e.ThumbError)
}
return e.Next()
})
},
ExpectedStatus: 200,
ExpectedContent: []string{string(testThumbFit)},
ExpectedEvents: map[string]int{
@@ -236,9 +276,17 @@ func TestFileDownload(t *testing.T) {
},
},
{
Name: "existing image - existing thumb (zero width)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=0x50",
Name: "existing image - existing thumb (zero width)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=0x50",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnFileDownloadRequest().BindFunc(func(e *core.FileDownloadRequestEvent) error {
if e.ThumbError != nil {
t.Fatalf("Expected no thumb error, got %v", e.ThumbError)
}
return e.Next()
})
},
ExpectedStatus: 200,
ExpectedContent: []string{string(testThumbZeroWidth)},
ExpectedEvents: map[string]int{
@@ -247,9 +295,17 @@ func TestFileDownload(t *testing.T) {
},
},
{
Name: "existing image - existing thumb (zero height)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=70x0",
Name: "existing image - existing thumb (zero height)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=70x0",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnFileDownloadRequest().BindFunc(func(e *core.FileDownloadRequestEvent) error {
if e.ThumbError != nil {
t.Fatalf("Expected no thumb error, got %v", e.ThumbError)
}
return e.Next()
})
},
ExpectedStatus: 200,
ExpectedContent: []string{string(testThumbZeroHeight)},
ExpectedEvents: map[string]int{
@@ -258,9 +314,17 @@ func TestFileDownload(t *testing.T) {
},
},
{
Name: "existing non image file - thumb parameter should be ignored",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/oap640cot4yru2s/test_kfd2wYLxkz.txt?thumb=100x100",
Name: "existing non image file - thumb parameter should be ignored",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/oap640cot4yru2s/test_kfd2wYLxkz.txt?thumb=100x100",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnFileDownloadRequest().BindFunc(func(e *core.FileDownloadRequestEvent) error {
if e.ThumbError == nil {
t.Fatal("Expected thumb error, got nil")
}
return e.Next()
})
},
ExpectedStatus: 200,
ExpectedContent: []string{string(testFile)},
ExpectedEvents: map[string]int{
@@ -289,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,
+1
View File
@@ -25,6 +25,7 @@ func healthCheck(e *core.RequestEvent) error {
Message: "API is healthy.",
}
// @todo evaluate whether it is worth removing the extra info from the health endpoint
if e.HasSuperuserAuth() {
resp.Data = make(map[string]any, 3)
resp.Data["canBackup"] = !e.App.Store().Has(core.StoreKeyActiveBackup)
+7 -1
View File
@@ -12,6 +12,7 @@ import (
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/osutils"
"github.com/pocketbase/pocketbase/ui"
)
// DefaultInstallerFunc is the default PocketBase installer function.
@@ -22,13 +23,18 @@ import (
//
// See https://github.com/pocketbase/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())
return nil
}
token, err := systemSuperuser.NewStaticAuthToken(30 * time.Minute)
if err != nil {
return err
}
// launch url (ignore errors and always print a help text as fallback)
url := fmt.Sprintf("%s/_/#/pbinstal/%s", strings.TrimRight(baseURL, "/"), token)
url := fmt.Sprintf("%s/_/#/pbinstall/%s", strings.TrimRight(baseURL, "/"), token)
_ = osutils.LaunchURL(url)
color.Magenta("\n(!) Launch the URL below in the browser if it hasn't been open already to create your first superuser account:")
color.New(color.Bold).Add(color.FgCyan).Println(url)
+22 -1
View File
@@ -11,8 +11,13 @@ import (
// bindLogsApi registers the request logs api endpoints.
func bindLogsApi(app core.App, rg *router.RouterGroup[*core.RequestEvent]) {
sub := rg.Group("/logs").Bind(RequireSuperuserAuth(), SkipSuccessActivityLog())
sub := rg.Group("/logs").Bind(
RequireSuperuserAuth(),
SkipSuccessActivityLog(),
)
sub.GET("", logsList)
sub.DELETE("", logsTruncate)
sub.GET("/stats", logsStats)
sub.GET("/{id}", logsView)
}
@@ -71,3 +76,19 @@ func logsView(e *core.RequestEvent) error {
return e.JSON(http.StatusOK, log)
}
func logsTruncate(e *core.RequestEvent) error {
// delete all rows directly (aka. no model hooks will be fired)
_, err := e.App.AuxNonconcurrentDB().Delete((&core.Log{}).TableName(), nil).Execute()
if err != nil {
return e.InternalServerError("Failed to truncate all logs.", err)
}
// try to free the unused disk space
err = e.App.AuxVacuum()
if err != nil {
e.App.Logger().Warn("Failed to VACUUM aux database", "error", err)
}
return e.NoContent(http.StatusNoContent)
}
+56
View File
@@ -210,3 +210,59 @@ func TestLogsStats(t *testing.T) {
scenario.Test(t)
}
}
func TestLogsTruncate(t *testing.T) {
t.Parallel()
scenarios := []tests.ApiScenario{
{
Name: "unauthorized",
Method: http.MethodDelete,
URL: "/api/logs",
ExpectedStatus: 401,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as regular user",
Method: http.MethodDelete,
URL: "/api/logs",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "authorized as superuser",
Method: http.MethodDelete,
URL: "/api/logs",
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := tests.StubLogsData(app); err != nil {
t.Fatal(err)
}
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
var found []core.Log
if err := app.LogQuery().All(&found); err != nil {
t.Fatal(err)
}
if len(found) > 0 {
t.Fatalf("Expected all logs to be deleted, found: %v", found)
}
},
ExpectedStatus: 204,
ExpectedEvents: map[string]int{"*": 0},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
+32 -4
View File
@@ -42,6 +42,9 @@ const (
DefaultLoadAuthTokenMiddlewarePriority = DefaultRateLimitMiddlewarePriority - 20
DefaultLoadAuthTokenMiddlewareId = "pbLoadAuthToken"
DefaultSuperuserIPsWhitelistMiddlewarePriority = DefaultLoadAuthTokenMiddlewarePriority + 5
DefaultSuperuserIPsWhitelistMiddlewareId = "pbSuperuserIPsWhitelist"
DefaultSecurityHeadersMiddlewarePriority = DefaultRateLimitMiddlewarePriority - 10
DefaultSecurityHeadersMiddlewareId = "pbSecurityHeaders"
@@ -207,11 +210,13 @@ func loadAuthToken() *hook.Handler[*core.RequestEvent] {
func getAuthTokenFromRequest(e *core.RequestEvent) string {
token := e.Request.Header.Get("Authorization")
if token != "" {
// the schema prefix is not required and it is only for
// compatibility with the defaults of some HTTP clients
token = strings.TrimPrefix(token, "Bearer ")
// the "Bearer" schema prefix is not required by PocketBase and it is
// supported only for compatibility with the defaults of some HTTP clients
if len(token) > 7 && strings.EqualFold(token[:7], "Bearer ") {
return token[7:]
}
return token
}
@@ -288,6 +293,7 @@ func securityHeaders() *hook.Handler[*core.RequestEvent] {
e.Response.Header().Set("X-XSS-Protection", "1; mode=block")
e.Response.Header().Set("X-Content-Type-Options", "nosniff")
e.Response.Header().Set("X-Frame-Options", "SAMEORIGIN")
e.Response.Header().Set("Cross-Origin-Opener-Policy", "same-origin")
// @todo consider a default HSTS?
// (see also https://webkit.org/blog/8146/protecting-against-hsts-abuse/)
@@ -297,6 +303,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] {
+15 -3
View File
@@ -11,7 +11,7 @@ import (
var ErrRequestEntityTooLarge = router.NewApiError(http.StatusRequestEntityTooLarge, "Request entity too large", nil)
const DefaultMaxBodySize int64 = 32 << 20
const DefaultMaxBodySize int64 = 32 << 20 // @todo consider replacing with router.DefaultMaxMemory
const (
DefaultBodyLimitMiddlewareId = "pbBodyLimit"
@@ -112,9 +112,21 @@ func (r *limitedReader) Read(b []byte) (int, error) {
return n, nil
}
// explicit casts to ensure that the main struct methods will be invoked
// (extra precautions in case of nested interface wrapping erasure)
// ---
func (r *limitedReader) Reread() {
rr, ok := r.ReadCloser.(router.Rereader)
rereader, ok := r.ReadCloser.(router.Rereader)
if ok {
rr.Reread()
rereader.Reread()
}
}
func (r *limitedReader) Close() error {
closer, ok := r.ReadCloser.(io.Closer)
if ok {
return closer.Close()
}
return nil
}
+55 -37
View File
@@ -2,6 +2,7 @@ package apis
import (
"errors"
"net/netip"
"sync"
"time"
@@ -106,30 +107,43 @@ func checkCollectionRateLimit(e *core.RequestEvent, collection *core.Collection,
return nil
}
// -------------------------------------------------------------------
// @todo consider exporting as helper?
//
//nolint:unused
func isClientRateLimited(e *core.RequestEvent, rtId string) bool {
rateLimiters, ok := e.App.Store().Get(rateLimitersStoreKey).(*store.Store[string, *rateLimiter])
if !ok || rateLimiters == 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
}
rt, ok := rateLimiters.GetOk(rtId)
if !ok || rt == nil {
// normalize
searchAddr, err := netip.ParseAddr(ip)
if err != nil {
return false
}
client, ok := rt.getClient(e.RealIP())
if !ok || client == 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 client.available <= 0 && time.Now().Unix()-client.lastConsume < client.interval
return false
}
// -------------------------------------------------------------------
// @todo consider exporting as helper?
func checkRateLimit(e *core.RequestEvent, rtId string, rule core.RateLimitRule) error {
switch rule.Audience {
@@ -154,7 +168,7 @@ func checkRateLimit(e *core.RequestEvent, rtId string, rule core.RateLimitRule)
}
rt := rateLimiters.GetOrSet(rtId, func() *rateLimiter {
return newRateLimiter(rule.MaxRequests, rule.Duration, rule.Duration+1800)
return newRateLimiter(rule.MaxRequests, rule.Duration, 1800)
})
if rt == nil {
e.App.Logger().Warn("Failed to retrieve app rate limiter", "id", rtId)
@@ -175,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}
@@ -234,12 +250,12 @@ func newRateLimiter(maxAllowed int, intervalInSec int64, minDeleteIntervalInSec
maxAllowed: maxAllowed,
interval: intervalInSec,
minDeleteInterval: minDeleteIntervalInSec,
clients: map[string]*fixedWindow{},
clients: map[string]*rateClient{},
}
}
type rateLimiter struct {
clients map[string]*fixedWindow
clients map[string]*rateClient
maxAllowed int
interval int64
@@ -250,7 +266,7 @@ type rateLimiter struct {
}
//nolint:unused
func (rt *rateLimiter) getClient(key string) (*fixedWindow, bool) {
func (rt *rateLimiter) getClient(key string) (*rateClient, bool) {
rt.RLock()
client, ok := rt.clients[key]
rt.RUnlock()
@@ -269,7 +285,7 @@ func (rt *rateLimiter) isAllowed(key string) bool {
// check again in case the client was added by another request
client, ok = rt.clients[key]
if !ok {
client = newFixedWindow(rt.maxAllowed, rt.interval)
client = newRateClient(rt.maxAllowed, rt.interval)
rt.clients[key] = client
}
rt.Unlock()
@@ -295,7 +311,7 @@ func (rt *rateLimiter) clean() {
//
// @todo remove after https://github.com/golang/go/issues/20135
if rt.totalDeleted >= 300 {
shrunk := make(map[string]*fixedWindow, len(rt.clients))
shrunk := make(map[string]*rateClient, len(rt.clients))
for k, v := range rt.clients {
shrunk[k] = v
}
@@ -304,52 +320,54 @@ func (rt *rateLimiter) clean() {
}
}
func newFixedWindow(maxAllowed int, intervalInSec int64) *fixedWindow {
return &fixedWindow{
func newRateClient(maxAllowed int, intervalInSec int64) *rateClient {
return &rateClient{
maxAllowed: maxAllowed,
interval: intervalInSec,
}
}
type fixedWindow struct {
// @todo evaluate swiching to sliding window with approximation counter similar to Cloudflare.
//
// rateClient implements fixed window rate limit strategy.
type rateClient struct {
// use plain Mutex instead of RWMutex since the operations are expected
// to be mostly writes (e.g. consume()) and it should perform better
sync.Mutex
maxAllowed int // the max allowed tokens per interval
available int // the total available tokens
interval int64 // in seconds
lastConsume int64 // the time of the last consume
maxAllowed int // the max allowed tokens per interval
available int // the total available tokens
start int64 // the start time of the current window
interval int64 // in seconds
}
// hasExpired checks whether it has been at least minElapsed seconds since the lastConsume time.
// hasExpired checks whether it has been at least minElapsed seconds after the last active window.
// (usually used to perform periodic cleanup of staled instances).
func (l *fixedWindow) hasExpired(relativeNow int64, minElapsed int64) bool {
func (l *rateClient) hasExpired(relativeNow int64, minElapsed int64) bool {
l.Lock()
defer l.Unlock()
return relativeNow-l.lastConsume > minElapsed
return relativeNow-(l.start+l.interval) > minElapsed
}
// consume decrease the current window allowance with 1 (if not exhausted already).
// consume decreases the current allowance with 1 (if not exhausted already).
//
// It returns false if the allowance has been already exhausted and the user
// has to wait until it resets back to its maxAllowed value.
func (l *fixedWindow) consume() bool {
func (l *rateClient) consume() bool {
l.Lock()
defer l.Unlock()
nowUnix := time.Now().Unix()
// reset consumed counter
if nowUnix-l.lastConsume >= l.interval {
// reset
if nowUnix-l.start >= l.interval {
l.available = l.maxAllowed
l.start = nowUnix
}
if l.available > 0 {
l.available--
l.lastConsume = nowUnix
return true
}
+180 -13
View File
@@ -1,13 +1,16 @@
package apis_test
import (
"fmt"
"net/http/httptest"
"testing"
"testing/synctest"
"time"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/hook"
)
func TestDefaultRateLimitMiddleware(t *testing.T) {
@@ -74,7 +77,7 @@ func TestDefaultRateLimitMiddleware(t *testing.T) {
scenarios := []struct {
url string
wait float64
wait float64 // ms
authenticated bool
expectedStatus int
}{
@@ -85,10 +88,12 @@ func TestDefaultRateLimitMiddleware(t *testing.T) {
{"/norate", 0, false, 200},
{"/rate/a", 0, 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},
{"/rate/a", 1.1, false, 200},
{"/rate/a", 1000, false, 200},
{"/rate/a", 0, false, 200},
{"/rate/a", 0, false, 429},
@@ -96,7 +101,7 @@ func TestDefaultRateLimitMiddleware(t *testing.T) {
{"/rate/b", 0, false, 200},
{"/rate/b", 0, false, 200},
{"/rate/b", 0, false, 429},
{"/rate/b", 1.1, false, 200},
{"/rate/b", 1000, false, 200},
{"/rate/b", 0, false, 200},
{"/rate/b", 0, false, 200},
{"/rate/b", 0, false, 429},
@@ -118,17 +123,15 @@ func TestDefaultRateLimitMiddleware(t *testing.T) {
{"/rate/guest", 0, false, 429},
// "guest" rule with regular user (should fallback to the /rate/ rule)
{"/rate/guest", 1.1, true, 200},
{"/rate/guest", 1000, true, 200},
{"/rate/guest", 0, true, 200},
{"/rate/guest", 0, true, 429},
{"/rate/guest", 0, true, 429},
}
for _, s := range scenarios {
t.Run(s.url, func(t *testing.T) {
if s.wait > 0 {
time.Sleep(time.Duration(s.wait) * time.Second)
}
synctest.Test(t, func(t *testing.T) {
for i, s := range scenarios {
prefix := fmt.Sprintf("[%s:%d] ", s.url, i+1)
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", s.url, nil)
@@ -136,24 +139,188 @@ func TestDefaultRateLimitMiddleware(t *testing.T) {
if s.authenticated {
auth, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
t.Fatalf(prefix+"%v", err)
}
token, err := auth.NewAuthToken()
if err != nil {
t.Fatal(err)
t.Fatalf(prefix+"%v", err)
}
req.Header.Add("Authorization", token)
}
if s.wait > 0 {
synctest.Sleep(time.Duration(s.wait) * time.Millisecond)
}
mux.ServeHTTP(rec, req)
result := rec.Result()
if result.StatusCode != s.expectedStatus {
t.Fatalf("Expected response status %d, got %d", s.expectedStatus, result.StatusCode)
t.Fatalf(prefix+"Expected response status %d, got %d", s.expectedStatus, result.StatusCode)
}
})
}
})
}
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})
})
}
+109
View File
@@ -224,6 +224,22 @@ func TestRequireAuth(t *testing.T) {
ExpectedStatus: 200,
ExpectedContent: []string{"test123"},
},
{
Name: "valid record auth token with Bearer case-insensitive prefix",
Method: http.MethodGet,
URL: "/my/test",
Headers: map[string]string{
// regular user
"Authorization": "BeArEr eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireAuth())
},
ExpectedStatus: 200,
ExpectedContent: []string{"test123"},
},
}
for _, scenario := range scenarios {
@@ -537,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)
}
}
+149 -24
View File
@@ -2,7 +2,7 @@ package apis
import (
"context"
"encoding/json"
"encoding/json/v2"
"errors"
"fmt"
"log/slog"
@@ -10,8 +10,8 @@ import (
"strings"
"time"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/dbx"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/picker"
@@ -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")
@@ -63,8 +66,12 @@ func realtimeConnect(e *core.RequestEvent) error {
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()
@@ -769,7 +890,11 @@ func realtimeCanAccessRecord(
}
q.AndWhere(expr)
resolver.UpdateQuery(q)
err = resolver.UpdateQuery(q)
if err != nil {
return false
}
err = q.Limit(1).Row(&exists)
+375 -19
View File
@@ -2,7 +2,7 @@ package apis_test
import (
"context"
"encoding/json"
"encoding/json/v2"
"errors"
"fmt"
"net/http"
@@ -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 {
@@ -817,7 +1171,9 @@ func TestRealtimeRecordResolve(t *testing.T) {
var mu sync.Mutex
notify := func(clientId string, eventData []byte) {
data := struct{ Action string }{}
data := struct {
Action string `json:"action"`
}{}
_ = json.Unmarshal(eventData, &data)
mu.Lock()
+7 -7
View File
@@ -3,7 +3,7 @@ package apis
import (
"net/http"
validation "github.com/go-ozzo/ozzo-validation/v4"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/security"
)
@@ -102,12 +102,6 @@ func (form *EmailChangeConfirmForm) parseToken() (*core.Record, string, error) {
return nil, "", validation.NewError("validation_invalid_token_payload", "Invalid token payload - newEmail must be set.")
}
// ensure that there aren't other users with the new email
_, err := form.app.FindAuthRecordByEmail(form.collection, newEmail)
if err == nil {
return nil, "", validation.NewError("validation_existing_token_email", "The new email address is already registered: "+newEmail)
}
// verify that the token is not expired and its signature is valid
authRecord, err := form.app.FindAuthRecordByToken(form.Token, core.TokenTypeEmailChange)
if err != nil {
@@ -118,5 +112,11 @@ func (form *EmailChangeConfirmForm) parseToken() (*core.Record, string, error) {
return nil, "", validation.NewError("validation_token_collection_mismatch", "The provided token is for different auth collection.")
}
// check if there are other users with the new email
_, err = form.app.FindAuthRecordByEmail(form.collection, newEmail)
if err == nil {
return nil, "", validation.NewError("validation_invalid_token_email", "The new email address is invalid.")
}
return authRecord, newEmail, nil
}
+40 -1
View File
@@ -111,12 +111,51 @@ func TestRecordConfirmEmailChange(t *testing.T) {
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
"OnRecordValidate": 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)
}
if user.Verified() {
t.Fatalf("Expected the user to be unverified before the confirmation")
}
// 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) {
_, err := app.FindAuthRecordByEmail("users", "change@example.com")
user, err := app.FindAuthRecordByEmail("users", "change@example.com")
if err != nil {
t.Fatalf("Expected to find user with email %q, got error: %v", "change@example.com", err)
}
if !user.Verified() {
t.Fatalf("Expected the user to be verified after the confirmation")
}
// 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))
}
},
},
{
+2 -2
View File
@@ -3,8 +3,8 @@ package apis
import (
"net/http"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/pocketbase/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/mails"
)
+2 -2
View File
@@ -3,7 +3,7 @@ package apis
import (
"time"
validation "github.com/go-ozzo/ozzo-validation/v4"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core"
)
@@ -34,7 +34,7 @@ func recordAuthImpersonate(e *core.RequestEvent) error {
token, err := record.NewStaticAuthToken(time.Duration(form.Duration) * time.Second)
if err != nil {
e.InternalServerError("Failed to generate static auth token", err)
return e.InternalServerError("Failed to generate static auth token", err)
}
return recordAuthResponse(e, record, token, "", nil)
+10 -1
View File
@@ -34,6 +34,7 @@ type oauth2Response struct {
type providerInfo struct {
Name string `json:"name"`
DisplayName string `json:"displayName"`
Logo string `json:"logo"`
State string `json:"state"`
AuthURL string `json:"authURL"`
@@ -68,7 +69,14 @@ func (amr *authMethodsResponse) fillLegacyFields() {
amr.UsernamePassword = amr.Password.Enabled && slices.Contains(amr.Password.IdentityFields, "username")
if amr.OAuth2.Enabled {
amr.AuthProviders = amr.OAuth2.Providers
// clone without the logo
legacyProviders := make([]providerInfo, len(amr.OAuth2.Providers))
for i, p := range amr.OAuth2.Providers {
legacyProviders[i] = p
legacyProviders[i].Logo = ""
}
amr.AuthProviders = legacyProviders
}
}
@@ -128,6 +136,7 @@ func recordAuthMethods(e *core.RequestEvent) error {
info := providerInfo{
Name: config.Name,
DisplayName: provider.DisplayName(),
Logo: provider.Logo(),
State: security.RandomString(30),
}
+2
View File
@@ -54,6 +54,8 @@ func TestRecordAuthMethodsList(t *testing.T) {
`"providers":[{`,
`"name":"google"`,
`"name":"gitlab"`,
`"logo":"<svg`,
`"logo":""`, // for the legacy fields
`"state":`,
`"displayName":`,
`"codeVerifier":`,
+2 -2
View File
@@ -6,8 +6,8 @@ import (
"fmt"
"net/http"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/pocketbase/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/mails"
"github.com/pocketbase/pocketbase/tools/routine"
+1 -1
View File
@@ -3,7 +3,7 @@ package apis
import (
"net/http"
validation "github.com/go-ozzo/ozzo-validation/v4"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/core/validators"
"github.com/pocketbase/pocketbase/tools/security"
@@ -114,11 +114,18 @@ func TestRecordConfirmPasswordReset(t *testing.T) {
"OnModelUpdate": 1,
"OnModelUpdateExecute": 1,
"OnModelAfterUpdateSuccess": 1,
"OnModelValidate": 1,
"OnRecordUpdate": 1,
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
"OnModelValidate": 1,
"OnRecordValidate": 1,
// ---
"OnModelDelete": 2, // pre-existing OAuth2 links
"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")
@@ -151,6 +158,15 @@ func TestRecordConfirmPasswordReset(t *testing.T) {
if !user.ValidatePassword("1234567!") {
t.Fatal("Password wasn't changed")
}
// 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))
}
},
},
{
@@ -221,6 +237,15 @@ func TestRecordConfirmPasswordReset(t *testing.T) {
if !user.ValidatePassword("1234567!") {
t.Fatal("Password wasn't changed")
}
// ensure that all pre-existing OAuth2 were NOT deleted
externalAuths, err := app.FindAllExternalAuthsByRecord(user)
if err != nil {
t.Fatal(err)
}
if len(externalAuths) != 2 {
t.Fatalf("Expected 2 external auths, found %d", len(externalAuths))
}
},
},
{
@@ -251,11 +276,20 @@ func TestRecordConfirmPasswordReset(t *testing.T) {
t.Fatalf("Failed to fetch confirm password user: %v", err)
}
oldTokenKey := user.TokenKey()
// ensure that the user is already verified
user.SetVerified(true)
if err := app.Save(user); err != nil {
t.Fatalf("Failed to update user verified state")
}
// resave with the old token key since the verified change above
// would refresh it and will make the password token invalid
user.SetTokenKey(oldTokenKey)
if err = app.Save(user); err != nil {
t.Fatalf("Failed to restore original user tokenKey: %v", err)
}
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
_, err := app.FindAuthRecordByToken(
+2 -2
View File
@@ -6,8 +6,8 @@ import (
"net/http"
"time"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/pocketbase/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/mails"
"github.com/pocketbase/pocketbase/tools/routine"
+8 -1
View File
@@ -3,7 +3,7 @@ package apis
import (
"net/http"
validation "github.com/go-ozzo/ozzo-validation/v4"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/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))
}
@@ -105,6 +105,130 @@ func TestRecordConfirmVerification(t *testing.T) {
"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)
}
if user.Verified() {
t.Fatal("Expected the user to be unverified before the confirmation")
}
// 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")
}
// 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 (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))
}
},
},
{
+2 -2
View File
@@ -6,8 +6,8 @@ import (
"net/http"
"time"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/pocketbase/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/mails"
"github.com/pocketbase/pocketbase/tools/routine"
+140 -18
View File
@@ -1,23 +1,29 @@
package apis
import (
"bytes"
"context"
"database/sql"
"encoding/json"
"encoding/json/v2"
"errors"
"fmt"
"io"
"log/slog"
"maps"
"net"
"net/http"
"path"
"strings"
"syscall"
"time"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/dbx"
validation "github.com/pocketbase/ozzo-validation/v4"
"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"
"golang.org/x/oauth2"
)
@@ -197,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),
)
}
@@ -213,16 +218,31 @@ func (form *recordOAuth2LoginForm) checkProviderName(value any) error {
return nil
}
// @todo evaluate if it is still worth keeping as this exists only for backward-compatibility with pre v0.23 versions
func oldCanAssignUsername(txApp core.App, collection *core.Collection, username string) bool {
field := collection.Fields.GetByName(collection.OAuth2.MappedFields.Username)
if field == nil {
return false
}
// ensure that the value matches the pattern of the username field (if text)
if txtField, ok := field.(*core.TextField); ok && txtField.ValidatePlainValue(username) != nil {
return false
}
// ensure that username is unique
index, hasUniqueue := dbutils.FindSingleColumnUniqueIndex(collection.Indexes, collection.OAuth2.MappedFields.Username)
index, hasUniqueue := dbutils.FindSingleColumnUniqueIndex(collection.Indexes, field.GetName())
if hasUniqueue {
// it is not required because collection fields are already sanitized
// but normalize as an extra precaution in case of a custom validator
colName := inflector.Columnify(field.GetName())
var expr dbx.Expression
if strings.EqualFold(index.Columns[0].Collate, "nocase") {
// case-insensitive search
expr = dbx.NewExp("username = {:username} COLLATE NOCASE", dbx.Params{"username": username})
expr = dbx.NewExp("[["+colName+"]] = {:username} COLLATE NOCASE", dbx.Params{"username": username})
} else {
expr = dbx.HashExp{"username": username}
expr = dbx.HashExp{colName: username}
}
var exists int
@@ -232,10 +252,7 @@ func oldCanAssignUsername(txApp core.App, collection *core.Collection, username
}
}
// ensure that the value matches the pattern of the username field (if text)
txtField, _ := collection.Fields.GetByName(collection.OAuth2.MappedFields.Username).(*core.TextField)
return txtField != nil && txtField.ValidatePlainValue(username) == nil
return true
}
func oauth2Submit(e *core.RecordAuthWithOAuth2RequestEvent, optExternalAuth *core.ExternalAuth) error {
@@ -281,9 +298,12 @@ func oauth2Submit(e *core.RecordAuthWithOAuth2RequestEvent, optExternalAuth *cor
if mappedField != nil && mappedField.Type() == core.FieldTypeFile {
// download the avatar if the mapped field is a file
avatarFile, err := func() (*filesystem.File, error) {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return filesystem.NewFileFromURL(ctx, e.OAuth2User.AvatarURL)
// the extra checks are not required because the OAuth2 APIs are trusted vendor
// but are here to minimize the impact in case the provider is vulnerable
return safeFileFromURL(ctx, e.OAuth2User.AvatarURL)
}()
if err != nil {
txApp.Logger().Warn("Failed to retrieve OAuth2 avatar", slog.String("error", err.Error()))
@@ -317,26 +337,43 @@ func oauth2Submit(e *core.RecordAuthWithOAuth2RequestEvent, optExternalAuth *cor
e.Auth.Id == e.Record.Id &&
e.Auth.Collection().Id == e.Record.Collection().Id
// set random password for users with unverified email
// (this is in case a malicious actor has registered previously with the user email)
if !isLoggedAuthRecord && e.Record.Email() != "" && !e.Record.Verified() {
e.Record.SetRandomPassword()
// prevent pre-hijacking with password auth
//
// reset the unverified user password in case the record was precreated by a malicious actor
if !isLoggedAuthRecord && !e.Record.Verified() {
needUpdate = true
e.Record.SetRandomPassword()
}
// prevent pre-hijacking with different OAuth2 provider
//
// delete all other previous OAuth2 record links for the cases
// when the user was precreated by malicious OAuth2 auth with custom payload data
//
// while this would be also done automatically on unverified -> verified upgrade,
// doing it manually here ensures that a single unverified record could have
// max 1 OAuth2 link to prevent further abuse when mixed with other auth flows
if !e.Record.Verified() {
err := txApp.DeleteAllExternalAuthsByRecord(e.Record)
if err != nil {
return err
}
optExternalAuth = nil // clear to allow recreate below
}
// update the existing auth record empty email if the data.OAuth2User has one
// (this is in case previously the auth record was created
// with an OAuth2 provider that didn't return an email address)
if e.Record.Email() == "" && e.OAuth2User.Email != "" {
e.Record.SetEmail(e.OAuth2User.Email)
needUpdate = true
e.Record.SetEmail(e.OAuth2User.Email)
}
// update the existing auth record verified state
// (only if the auth record doesn't have an email or the auth record email match with the one in data.OAuth2User)
if !e.Record.Verified() && (e.Record.Email() == "" || e.Record.Email() == e.OAuth2User.Email) {
e.Record.SetVerified(true)
needUpdate = true
e.Record.SetVerified(true)
}
if needUpdate {
@@ -386,3 +423,88 @@ func sendOAuth2RecordCreateRequest(txApp core.App, e *core.RecordAuthWithOAuth2R
return createdRecord, nil
}
// -------------------------------------------------------------------
// safeHTTPClient initializes a custom http.Client with extra host checks
// to prevent internal network probing requests
// (aka. disallow loopback, private, multicast, etc. requests).
//
// NB! The host checks are not perfect and there are probably edge cases that are not covered,
// so if you plan using with untrusted user URL, consider performing additional whitelist checks.
//
// @todo Evaluate with the refactoring if worth exporting(+tests) and moving under the security package.
func safeHTTPClient() *http.Client {
dialer := &net.Dialer{
// the same options as in http.DefaultTransport.DialContext
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
// check the address right after estrablishing the connection to prevent dns rebinding
Control: func(network, address string, c syscall.RawConn) error {
host, _, err := net.SplitHostPort(address)
if err != nil {
return err
}
ip := net.ParseIP(host)
if ip == nil ||
ip.IsLoopback() ||
ip.IsUnspecified() ||
ip.IsPrivate() ||
ip.IsLinkLocalUnicast() ||
ip.IsLinkLocalMulticast() ||
ip.IsMulticast() {
return fmt.Errorf("address %q is invalid or resolve to disallowed IP", address)
}
return nil
},
}
return &http.Client{
Timeout: 180 * time.Second, // can be still cancelled with the request context
Transport: &http.Transport{
DialContext: dialer.DialContext,
// the same options as in http.DefaultTransport
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
}
}
// safeFileFromURL downloads the file from the specified url (using safeHTTPClient)
// and creates a new filesystem.File value from its content (limited to DefaultMaxBodySize).
//
// @todo Evaluate with the refactoring if worth exporting/replacing filesystem.NewFileFromURL (or redefine as NewUnsafeFileFromURL).
func safeFileFromURL(ctx context.Context, url string) (*filesystem.File, error) {
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return nil, err
}
client := safeHTTPClient()
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode < 200 || res.StatusCode > 399 {
return nil, fmt.Errorf("failed to download url %s (%d)", url, res.StatusCode)
}
body := io.LimitReader(res.Body, DefaultMaxBodySize)
var buf bytes.Buffer
if _, err = io.Copy(&buf, body); err != nil {
return nil, err
}
return filesystem.NewFileFromBytes(buf.Bytes(), path.Base(url))
}
+44 -12
View File
@@ -1,7 +1,7 @@
package apis
import (
"encoding/json"
"encoding/json/v2"
"errors"
"net/http"
"strings"
@@ -9,6 +9,7 @@ import (
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/subscriptions"
"github.com/pocketbase/pocketbase/ui"
)
const (
@@ -28,17 +29,12 @@ type oauth2RedirectData struct {
}
func oauth2SubscriptionRedirect(e *core.RequestEvent) error {
redirectStatusCode := http.StatusTemporaryRedirect
if e.Request.Method != http.MethodGet {
redirectStatusCode = http.StatusSeeOther
}
data := oauth2RedirectData{}
if e.Request.Method == http.MethodPost {
if err := e.BindBody(&data); err != nil {
e.App.Logger().Debug("Failed to read OAuth2 redirect data", "error", err)
return e.Redirect(redirectStatusCode, oauth2RedirectFailurePath)
return failureRedirect(e)
}
} else {
query := e.Request.URL.Query()
@@ -49,16 +45,26 @@ func oauth2SubscriptionRedirect(e *core.RequestEvent) error {
if data.State == "" {
e.App.Logger().Debug("Missing OAuth2 state parameter")
return e.Redirect(redirectStatusCode, oauth2RedirectFailurePath)
return failureRedirect(e)
}
client, err := e.App.SubscriptionsBroker().ClientById(data.State)
if err != nil || client.IsDiscarded() || !client.HasSubscription(oauth2SubscriptionTopic) {
e.App.Logger().Debug("Missing or invalid OAuth2 subscription client", "error", err, "clientId", data.State)
return e.Redirect(redirectStatusCode, oauth2RedirectFailurePath)
return failureRedirect(e)
}
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)
if data.AppleUser != "" && data.Error == "" && data.Code != "" {
@@ -76,7 +82,7 @@ func oauth2SubscriptionRedirect(e *core.RequestEvent) error {
encodedData, err := json.Marshal(data)
if err != nil {
e.App.Logger().Debug("Failed to marshalize OAuth2 redirect data", "error", err)
return e.Redirect(redirectStatusCode, oauth2RedirectFailurePath)
return failureRedirect(e)
}
msg := subscriptions.Message{
@@ -88,10 +94,36 @@ func oauth2SubscriptionRedirect(e *core.RequestEvent) error {
if data.Error != "" || data.Code == "" {
e.App.Logger().Debug("Failed OAuth2 redirect due to an error or missing code parameter", "error", data.Error, "clientId", data.State)
return e.Redirect(redirectStatusCode, oauth2RedirectFailurePath)
return failureRedirect(e)
}
return e.Redirect(redirectStatusCode, oauth2RedirectSuccessPath)
return successRedirect(e)
}
func redirectStatusCode(e *core.RequestEvent) int {
if e.Request.Method != http.MethodGet {
return http.StatusSeeOther
}
return http.StatusTemporaryRedirect
}
func failureRedirect(e *core.RequestEvent) error {
// fallback if UI is not bundled
if ui.DistDirFS == nil {
return e.String(http.StatusOK, "Failed to authenticate. You can close this window and go back to the app to try again.")
}
return e.Redirect(redirectStatusCode(e), oauth2RedirectFailurePath)
}
func successRedirect(e *core.RequestEvent) error {
// fallback if UI is not bundled
if ui.DistDirFS == nil {
return e.HTML(http.StatusOK, "Auth completed. You can close this window and go back to the app.")
}
return e.Redirect(redirectStatusCode(e), oauth2RedirectSuccessPath)
}
// parseAndStoreAppleRedirectName extracts the first and last name
+25 -2
View File
@@ -8,6 +8,7 @@ import (
"testing"
"time"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/subscriptions"
@@ -16,9 +17,9 @@ import (
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 {
+337 -22
View File
@@ -45,12 +45,14 @@ func TestRecordAuthWithOAuth2(t *testing.T) {
t.Parallel()
// start a test server
server := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
localServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
buf := new(bytes.Buffer)
png.Encode(buf, image.Rect(0, 0, 1, 1)) // tiny 1x1 png
http.ServeContent(res, req, "test_avatar.png", time.Now(), bytes.NewReader(buf.Bytes()))
}))
defer server.Close()
defer localServer.Close()
externalImageURL := "https://pocketbase.io/images/logo.svg"
scenarios := []tests.ApiScenario{
{
@@ -88,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},
},
@@ -107,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},
},
@@ -176,6 +180,20 @@ func TestRecordAuthWithOAuth2(t *testing.T) {
t.Fatal(err)
}
// ensure that there is at least one other external auth different than test
// so that later we can verify that it was deleted
var hasAtLeastOneOtherEA = false
externalAuths, _ := app.FindAllExternalAuthsByRecord(user)
for _, rel := range externalAuths {
if rel.Id != ea.Id {
hasAtLeastOneOtherEA = true
break
}
}
if !hasAtLeastOneOtherEA {
t.Fatal("Expected at least one non-test external auth linked")
}
// test at least once that the correct request info context is properly loaded
app.OnRecordAuthRequest().BindFunc(func(e *core.RecordAuthRequestEvent) error {
info, err := e.RequestInfo()
@@ -211,12 +229,12 @@ func TestRecordAuthWithOAuth2(t *testing.T) {
"OnRecordAuthRequest": 1,
"OnRecordEnrich": 1,
// ---
"OnModelCreate": 1,
"OnModelCreateExecute": 1,
"OnModelAfterCreateSuccess": 1,
"OnRecordCreate": 1,
"OnRecordCreateExecute": 1,
"OnRecordAfterCreateSuccess": 1,
"OnModelCreate": 2, // user + recreated external auth
"OnModelCreateExecute": 2,
"OnModelAfterCreateSuccess": 2,
"OnRecordCreate": 2,
"OnRecordCreateExecute": 2,
"OnRecordAfterCreateSuccess": 2,
// ---
"OnModelUpdate": 1,
"OnModelUpdateExecute": 1,
@@ -225,8 +243,15 @@ func TestRecordAuthWithOAuth2(t *testing.T) {
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
// ---
"OnModelValidate": 2, // create + update
"OnRecordValidate": 2,
"OnModelDelete": 3, // pre-existing external auths
"OnModelDeleteExecute": 3,
"OnModelAfterDeleteSuccess": 3,
"OnRecordDelete": 3,
"OnRecordDeleteExecute": 3,
"OnRecordAfterDeleteSuccess": 3,
// ---
"OnModelValidate": 3, // user create/update + recreated external auth
"OnRecordValidate": 3,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
@@ -246,6 +271,24 @@ func TestRecordAuthWithOAuth2(t *testing.T) {
if len(devices) != 1 {
t.Fatalf("Expected only 1 auth origin to be created, got %d (%v)", len(devices), err)
}
// ensure that other linked external auths have been deleted
externalAuths, _ := app.FindAllExternalAuthsByRecord(user)
if len(externalAuths) != 1 {
t.Fatalf("Expected only 1 external auth to remain, got %d", len(externalAuths))
}
if provider := externalAuths[0].Provider(); provider != "test" {
t.Fatalf("Expected %q external auth, got %q", "test", provider)
}
if providerId := externalAuths[0].ProviderId(); providerId != "test_id" {
t.Fatalf("Expected %q providerId, got %q", "test_id", providerId)
}
if recordRef := externalAuths[0].RecordRef(); recordRef != user.Id {
t.Fatalf("Expected %q recordRef, got %q", user.Id, recordRef)
}
if collectionRef := externalAuths[0].CollectionRef(); collectionRef != user.Collection().Id {
t.Fatalf("Expected %q collectionRef, got %q", user.Collection().Id, collectionRef)
}
},
},
{
@@ -341,7 +384,7 @@ func TestRecordAuthWithOAuth2(t *testing.T) {
}
if !user.ValidatePassword("1234567890") {
t.Fatalf("Expected old password %q to be valid", "1234567890")
t.Fatalf("Expected old password %q to remain valid", "1234567890")
}
devices, err := app.FindAllAuthOriginsByRecord(user)
@@ -351,7 +394,7 @@ func TestRecordAuthWithOAuth2(t *testing.T) {
},
},
{
Name: "link by email",
Name: "link by email (unverified user)",
Method: http.MethodPost,
URL: "/api/collections/users/auth-with-oauth2",
Body: strings.NewReader(`{
@@ -374,6 +417,20 @@ func TestRecordAuthWithOAuth2(t *testing.T) {
t.Fatalf("Expected password %q to be valid", "1234567890")
}
// ensure that there is at least one other external auth different than test
// so that later we can verify that it was deleted
var hasAtLeastOneOtherEA = false
externalAuths, _ := app.FindAllExternalAuthsByRecord(user)
for _, rel := range externalAuths {
if rel.Provider() != "test" {
hasAtLeastOneOtherEA = true
break
}
}
if !hasAtLeastOneOtherEA {
t.Fatal("Expected at least one non-test external auth linked")
}
// register the test provider
auth.Providers["test"] = func() auth.Provider {
return &oauth2MockProvider{
@@ -430,6 +487,13 @@ func TestRecordAuthWithOAuth2(t *testing.T) {
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
// ---
"OnModelDelete": 2, // pre-existing external auths
"OnModelDeleteExecute": 2,
"OnModelAfterDeleteSuccess": 2,
"OnRecordDelete": 2,
"OnRecordDeleteExecute": 2,
"OnRecordAfterDeleteSuccess": 2,
// ---
"OnModelValidate": 3, // record + authOrigins + externalAuths
"OnRecordValidate": 3,
},
@@ -447,6 +511,145 @@ func TestRecordAuthWithOAuth2(t *testing.T) {
if len(devices) != 1 {
t.Fatalf("Expected only 1 auth origin to be created, got %d (%v)", len(devices), err)
}
// ensure that other linked external auths have been deleted
externalAuths, _ := app.FindAllExternalAuthsByRecord(user)
if len(externalAuths) != 1 {
t.Fatalf("Expected only 1 external auth to remain, got %d", len(externalAuths))
}
if provider := externalAuths[0].Provider(); provider != "test" {
t.Fatalf("Expected %q external auth, got %q", "test", provider)
}
if providerId := externalAuths[0].ProviderId(); providerId != "test_id" {
t.Fatalf("Expected %q providerId, got %q", "test_id", providerId)
}
if recordRef := externalAuths[0].RecordRef(); recordRef != user.Id {
t.Fatalf("Expected %q recordRef, got %q", user.Id, recordRef)
}
if collectionRef := externalAuths[0].CollectionRef(); collectionRef != user.Collection().Id {
t.Fatalf("Expected %q collectionRef, got %q", user.Collection().Id, collectionRef)
}
},
},
{
Name: "link by email (verified user)",
Method: http.MethodPost,
URL: "/api/collections/users/auth-with-oauth2",
Body: strings.NewReader(`{
"provider": "test",
"code":"123",
"redirectURL": "https://example.com"
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
user, err := app.FindAuthRecordByEmail("users", "test3@example.com")
if err != nil {
t.Fatal(err)
}
if !user.Verified() {
t.Fatalf("Expected user %q to be verified", user.Email())
}
// ensure that the old password works
if !user.ValidatePassword("1234567890") {
t.Fatalf("Expected password %q to be valid", "1234567890")
}
// register the test provider
auth.Providers["test"] = func() auth.Provider {
return &oauth2MockProvider{
AuthUser: &auth.AuthUser{Id: "test_id", Email: "test3@example.com"},
Token: &oauth2.Token{AccessToken: "abc"},
}
}
// ensure that there is at least one other external auth different than test
// so that later we can verify that they are not deleted
var hasAtLeastOneOtherEA = false
externalAuths, _ := app.FindAllExternalAuthsByRecord(user)
for _, rel := range externalAuths {
if rel.Provider() != "test" {
hasAtLeastOneOtherEA = true
break
}
}
if !hasAtLeastOneOtherEA {
t.Fatal("Expected at least one non-test external auth linked")
}
// add the test provider in the collection
user.Collection().MFA.Enabled = false
user.Collection().OAuth2.Enabled = true
user.Collection().OAuth2.Providers = []core.OAuth2ProviderConfig{{
Name: "test",
ClientId: "123",
ClientSecret: "456",
}}
if err := app.Save(user.Collection()); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"record":{`,
`"token":"`,
`"meta":{`,
`"isNew":false`,
`"email":"test3@example.com"`,
`"id":"bgs820n361vj1qd"`,
`"id":"test_id"`,
`"verified":true`,
},
NotExpectedContent: []string{
// hidden fields
`"tokenKey"`,
`"password"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordAuthWithOAuth2Request": 1,
"OnRecordAuthRequest": 1,
"OnRecordEnrich": 1,
// ---
"OnModelCreate": 2, // authOrigins + externalAuths
"OnModelCreateExecute": 2,
"OnModelAfterCreateSuccess": 2,
"OnRecordCreate": 2,
"OnRecordCreateExecute": 2,
"OnRecordAfterCreateSuccess": 2,
// ---
"OnModelValidate": 2, // authOrigins + externalAuths
"OnRecordValidate": 2,
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
user, err := app.FindAuthRecordByEmail("users", "test3@example.com")
if err != nil {
t.Fatal(err)
}
if !user.ValidatePassword("1234567890") {
t.Fatalf("Expected old password %q to remain valid", "1234567890")
}
devices, err := app.FindAllAuthOriginsByRecord(user)
if len(devices) != 1 {
t.Fatalf("Expected only 1 auth origin to be created, got %d (%v)", len(devices), err)
}
var hasTestEA = false
externalAuths, err := app.FindAllExternalAuthsByRecord(user)
if len(externalAuths) <= 1 {
t.Fatalf("Expected to have 2+ ExternalAuth records, got %d (%v)", len(externalAuths), err)
}
for _, rel := range externalAuths {
if rel.Provider() == "test" {
hasTestEA = true
break
}
}
if !hasTestEA {
t.Fatal("Expected test external auth to be linked")
}
},
},
{
@@ -529,6 +732,13 @@ func TestRecordAuthWithOAuth2(t *testing.T) {
"OnRecordCreateExecute": 2,
"OnRecordAfterCreateSuccess": 2,
// ---
"OnModelDelete": 2, // pre-existing external auths
"OnModelDeleteExecute": 2,
"OnModelAfterDeleteSuccess": 2,
"OnRecordDelete": 2,
"OnRecordDeleteExecute": 2,
"OnRecordAfterDeleteSuccess": 2,
// ---
"OnModelValidate": 2,
"OnRecordValidate": 2,
},
@@ -539,7 +749,7 @@ func TestRecordAuthWithOAuth2(t *testing.T) {
}
if !user.ValidatePassword("1234567890") {
t.Fatalf("Expected password %q not to be changed", "1234567890")
t.Fatalf("Expected old password %q to remain valid", "1234567890")
}
devices, err := app.FindAllAuthOriginsByRecord(user)
@@ -650,6 +860,13 @@ func TestRecordAuthWithOAuth2(t *testing.T) {
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
// ---
"OnModelDelete": 2, // pre-existing external auths
"OnModelDeleteExecute": 2,
"OnModelAfterDeleteSuccess": 2,
"OnRecordDelete": 2,
"OnRecordDeleteExecute": 2,
"OnRecordAfterDeleteSuccess": 2,
// ---
"OnModelValidate": 3, // record + authOrigins + externalAuths
"OnRecordValidate": 3,
},
@@ -660,7 +877,7 @@ func TestRecordAuthWithOAuth2(t *testing.T) {
}
if !user.ValidatePassword("1234567890") {
t.Fatalf("Expected password %q not to be changed", "1234567890")
t.Fatalf("Expected old password %q to remain valid", "1234567890")
}
devices, err := app.FindAllAuthOriginsByRecord(user)
@@ -756,6 +973,13 @@ func TestRecordAuthWithOAuth2(t *testing.T) {
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
// ---
"OnModelDelete": 2, // pre-existing external auths
"OnModelDeleteExecute": 2,
"OnModelAfterDeleteSuccess": 2,
"OnRecordDelete": 2,
"OnRecordDeleteExecute": 2,
"OnRecordAfterDeleteSuccess": 2,
// ---
"OnModelValidate": 3, // record + authOrigins + externalAuths
"OnRecordValidate": 3,
},
@@ -766,7 +990,7 @@ func TestRecordAuthWithOAuth2(t *testing.T) {
}
if !user.ValidatePassword("1234567890") {
t.Fatalf("Expected password %q not to be changed", "1234567890")
t.Fatalf("Expected old password %q to remain valid", "1234567890")
}
devices, err := app.FindAllAuthOriginsByRecord(user)
@@ -1176,7 +1400,7 @@ func TestRecordAuthWithOAuth2(t *testing.T) {
Id: "oauth2_id",
Email: "oauth2@example.com",
Username: "oauth2_username",
AvatarURL: server.URL + "/oauth2_avatar.png",
AvatarURL: externalImageURL,
},
Token: &oauth2.Token{AccessToken: "abc"},
}
@@ -1208,7 +1432,98 @@ func TestRecordAuthWithOAuth2(t *testing.T) {
`"username":"oauth2_username"`,
`"verified":true`,
`"rel":"0yxhwia2amd8gec"`,
`"avatar":"oauth2_avatar_`,
`"avatar":"logo_`,
},
NotExpectedContent: []string{
// hidden fields
`"tokenKey"`,
`"password"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordAuthWithOAuth2Request": 1,
"OnRecordAuthRequest": 1,
"OnRecordCreateRequest": 1,
"OnRecordEnrich": 2, // the auth response and from the create request
// ---
"OnModelCreate": 3, // record + authOrigins + externalAuths
"OnModelCreateExecute": 3,
"OnModelAfterCreateSuccess": 3,
"OnRecordCreate": 3,
"OnRecordCreateExecute": 3,
"OnRecordAfterCreateSuccess": 3,
// ---
"OnModelUpdate": 1, // created record verified state change
"OnModelUpdateExecute": 1,
"OnModelAfterUpdateSuccess": 1,
"OnRecordUpdate": 1,
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
// ---
"OnModelValidate": 4,
"OnRecordValidate": 4,
},
},
{
Name: "creating user (with mapped OAuth2 fields and local avatarURL->file field; ensures that safeHTTPClient is being used)",
Method: http.MethodPost,
URL: "/api/collections/users/auth-with-oauth2",
Body: strings.NewReader(`{
"provider": "test",
"code":"123",
"redirectURL": "https://example.com",
"createData": {
"name": "test_name",
"emailVisibility": true,
"rel": "0yxhwia2amd8gec"
}
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
usersCol, err := app.FindCollectionByNameOrId("users")
if err != nil {
t.Fatal(err)
}
// register the test provider
auth.Providers["test"] = func() auth.Provider {
return &oauth2MockProvider{
AuthUser: &auth.AuthUser{
Id: "oauth2_id",
Email: "oauth2@example.com",
Username: "oauth2_username",
AvatarURL: localServer.URL + "/oauth2_avatar.png", // local/private file download is not allowed
},
Token: &oauth2.Token{AccessToken: "abc"},
}
}
// add the test provider in the collection
usersCol.MFA.Enabled = false
usersCol.OAuth2.Enabled = true
usersCol.OAuth2.Providers = []core.OAuth2ProviderConfig{{
Name: "test",
ClientId: "123",
ClientSecret: "456",
}}
usersCol.OAuth2.MappedFields = core.OAuth2KnownFields{
Username: "name", // should be ignored because of the explicit submitted value
Id: "username",
AvatarURL: "avatar",
}
if err := app.Save(usersCol); err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"isNew":true`,
`"email":"oauth2@example.com"`,
`"emailVisibility":true`,
`"name":"test_name"`,
`"username":"oauth2_username"`,
`"verified":true`,
`"rel":"0yxhwia2amd8gec"`,
`"avatar":"`,
},
NotExpectedContent: []string{
// hidden fields
@@ -1343,7 +1658,7 @@ func TestRecordAuthWithOAuth2(t *testing.T) {
Email: "oauth2@example.com",
Username: "tESt2_username", // wouldn't match with existing because the related field index is case-sensitive
Name: "oauth2_name",
AvatarURL: server.URL + "/oauth2_avatar.png",
AvatarURL: localServer.URL + "/oauth2_avatar.png", // allowed because it is not being downloaded
},
Token: &oauth2.Token{AccessToken: "abc"},
}
+22 -12
View File
@@ -4,7 +4,7 @@ import (
"errors"
"fmt"
validation "github.com/go-ozzo/ozzo-validation/v4"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core"
)
@@ -53,7 +53,7 @@ func recordAuthWithOTP(e *core.RequestEvent) error {
return e.BadRequestError("Invalid or expired OTP", fmt.Errorf("missing auth record: %w", err))
}
// since otps are usually simple digit numbers, enforce an extra rate limit rule as basic enumaration protection
// since otps are usually simple digit numbers, enforce an extra rate limit rule as basic enumeration protection
err = checkRateLimit(e, "@pb_otp_"+event.Record.Id, core.RateLimitRule{MaxRequests: 5, Duration: 180})
if err != nil {
return e.TooManyRequestsError("Too many attempts, please try again later with a new OTP.", nil)
@@ -65,28 +65,38 @@ func recordAuthWithOTP(e *core.RequestEvent) error {
// ---
return e.App.OnRecordAuthWithOTPRequest().Trigger(event, func(e *core.RecordAuthWithOTPRequestEvent) error {
otpId := e.OTP.Id
otpSentTo := e.OTP.SentTo()
// 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 {
e.App.Logger().Error("Failed to delete used OTP", "error", err, "otpId", e.OTP.Id)
}
// update the user email verified state in case the OTP originate from an email address matching the current record one
//
// note: don't wait for success auth response (it could fail because of MFA) and because we already validated the OTP above
otpSentTo := e.OTP.SentTo()
if !e.Record.Verified() && otpSentTo != "" && e.Record.Email() == otpSentTo {
e.Record.SetVerified(true)
err = e.App.Save(e.Record)
if err != nil {
// this is technically not required but we enforce password
// reset on verified upgrades in case the OTP is used on its own
// since this makes it less error prone to pre-hijacking attacks
if !e.Record.Collection().MFA.Enabled {
e.Record.SetRandomPassword()
}
if err := e.App.Save(e.Record); err != nil {
e.App.Logger().Error("Failed to update record verified state after successful OTP validation",
"error", err,
"otpId", e.OTP.Id,
"otpId", otpId,
"recordId", e.Record.Id,
)
}
}
// try to delete the used otp
err = e.App.Delete(e.OTP)
if err != nil {
e.App.Logger().Error("Failed to delete used OTP", "error", err, "otpId", e.OTP.Id)
}
return RecordAuthResponse(e.RequestEvent, e.Record, core.MFAMethodOTP, nil)
})
}
+43 -7
View File
@@ -327,6 +327,15 @@ func TestRecordAuthWithOTP(t *testing.T) {
if user.Verified() {
t.Fatal("Expected the user to remain unverified because sentTo != email")
}
// ensure that all pre-existing OAuth2 were NOT deleted
externalAuths, err := app.FindAllExternalAuthsByRecord(user)
if err != nil {
t.Fatal(err)
}
if len(externalAuths) != 2 {
t.Fatalf("Expected 2 external auths, found %d", len(externalAuths))
}
},
},
{
@@ -364,6 +373,15 @@ func TestRecordAuthWithOTP(t *testing.T) {
if err := app.Save(otp); err != nil {
t.Fatal(err)
}
// verify that there are 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 auth")
}
},
ExpectedStatus: 200,
ExpectedContent: []string{
@@ -388,10 +406,10 @@ func TestRecordAuthWithOTP(t *testing.T) {
"OnModelCreate": 1,
"OnModelCreateExecute": 1,
"OnModelAfterCreateSuccess": 1,
// OTP delete
"OnModelDelete": 1,
"OnModelDeleteExecute": 1,
"OnModelAfterDeleteSuccess": 1,
// record OTP + 2 ExternalAuths delete
"OnModelDelete": 3,
"OnModelDeleteExecute": 3,
"OnModelAfterDeleteSuccess": 3,
// user verified update
"OnModelUpdate": 1,
"OnModelUpdateExecute": 1,
@@ -401,9 +419,9 @@ func TestRecordAuthWithOTP(t *testing.T) {
"OnRecordCreate": 1,
"OnRecordCreateExecute": 1,
"OnRecordAfterCreateSuccess": 1,
"OnRecordDelete": 1,
"OnRecordDeleteExecute": 1,
"OnRecordAfterDeleteSuccess": 1,
"OnRecordDelete": 3,
"OnRecordDeleteExecute": 3,
"OnRecordAfterDeleteSuccess": 3,
"OnRecordUpdate": 1,
"OnRecordUpdateExecute": 1,
"OnRecordAfterUpdateSuccess": 1,
@@ -417,6 +435,24 @@ func TestRecordAuthWithOTP(t *testing.T) {
if !user.Verified() {
t.Fatal("Expected the user to be marked as verified")
}
// ensure that all pre-existing OTPs are cleared
otps, err := app.FindAllOTPsByRecord(user)
if err != nil {
t.Fatal(err)
}
if len(otps) > 0 {
t.Fatalf("Expected all OTPs to be cleared, found %d", len(otps))
}
// 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))
}
},
},
{
+45 -16
View File
@@ -6,9 +6,9 @@ import (
"slices"
"strings"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/dbx"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/pocketbase/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/dbutils"
"github.com/pocketbase/pocketbase/tools/list"
@@ -40,23 +40,32 @@ func recordAuthWithPassword(e *core.RequestEvent) error {
if form.IdentityField != "" {
foundRecord, foundErr = findRecordByIdentityField(e.App, collection, form.IdentityField, form.Identity)
} else {
// prioritize email lookup
isEmail := is.EmailFormat.Validate(form.Identity) == nil
if isEmail && list.ExistInSlice(core.FieldNameEmail, collection.PasswordAuth.IdentityFields) {
foundRecord, foundErr = findRecordByIdentityField(e.App, collection, core.FieldNameEmail, form.Identity)
identityFields := collection.PasswordAuth.IdentityFields
// @todo consider removing with the stable release or moving it in the collection save
//
// prioritize email lookup to minimize breaking changes with earlier versions
if len(identityFields) > 1 && identityFields[0] != core.FieldNameEmail {
identityFields = slices.Clone(identityFields)
slices.SortStableFunc(identityFields, func(a, b string) int {
if a == "email" {
return -1
}
if b == "email" {
return 1
}
return 0
})
}
// search by the other identity fields
if !isEmail || foundErr != nil {
for _, name := range collection.PasswordAuth.IdentityFields {
if !isEmail && name == core.FieldNameEmail {
continue // no need to search by the email field if it is not an email
}
for _, name := range identityFields {
if name == core.FieldNameEmail && is.EmailFormat.Validate(form.Identity) != nil {
continue // no need to query the database if we know that the submitted value is not an email
}
foundRecord, foundErr = findRecordByIdentityField(e.App, collection, name, form.Identity)
if foundErr == nil {
break
}
foundRecord, foundErr = findRecordByIdentityField(e.App, collection, name, form.Identity)
if foundErr == nil {
break
}
}
}
@@ -76,6 +85,11 @@ func recordAuthWithPassword(e *core.RequestEvent) error {
return e.App.OnRecordAuthWithPasswordRequest().Trigger(event, func(e *core.RecordAuthWithPasswordRequestEvent) error {
if e.Record == nil || !e.Record.ValidatePassword(e.Password) {
// dummy password check to minimize enumeration side-channel attacks
if e.Record == nil {
dummyPasswordCheck(e.App, e.Collection)
}
return e.BadRequestError("Failed to authenticate.", errors.New("invalid login credentials"))
}
@@ -106,6 +120,21 @@ func (form *authWithPasswordForm) validate(collection *core.Collection) error {
)
}
// dummy password check to minimize side-channel attacks
// (performed with the collection configured field cost)
func dummyPasswordCheck(app core.App, collection *core.Collection) {
record := &core.Record{}
// find any random existing record
err := app.RecordQuery(collection).Limit(1).One(record)
if err != nil {
return
}
// the value and result doesn't matter, we just need a constant-time check
_ = record.ValidatePassword("")
}
func findRecordByIdentityField(app core.App, collection *core.Collection, field string, value any) (*core.Record, error) {
if !slices.Contains(collection.PasswordAuth.IdentityFields, field) {
return nil, errors.New("invalid identity field " + field)
+51
View File
@@ -212,6 +212,57 @@ func TestRecordAuthWithPassword(t *testing.T) {
"OnMailerRecordAuthAlertSend": 1,
},
},
{
// https://github.com/pocketbase/pocketbase/issues/7256
Name: "valid non-email identity field with a value that is a properly formatted email",
Method: http.MethodPost,
URL: "/api/collections/clients/auth-with-password",
Body: strings.NewReader(`{
"identity":"username_as_email@example.com",
"password":"1234567890"
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
record, err := app.FindAuthRecordByEmail("clients", "test@example.com")
if err != nil {
t.Fatal(err)
}
record.Set("username", "username_as_email@example.com")
err = app.SaveNoValidate(record)
if err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"email":"test@example.com"`,
`"username":"username_as_email@example.com"`,
`"token":`,
},
NotExpectedContent: []string{
// hidden fields
`"tokenKey"`,
`"password"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordAuthWithPasswordRequest": 1,
"OnRecordAuthRequest": 1,
"OnRecordEnrich": 1,
// authOrigin track
"OnModelCreate": 1,
"OnModelCreateExecute": 1,
"OnModelAfterCreateSuccess": 1,
"OnModelValidate": 1,
"OnRecordCreate": 1,
"OnRecordCreateExecute": 1,
"OnRecordAfterCreateSuccess": 1,
"OnRecordValidate": 1,
"OnMailerSend": 1,
"OnMailerRecordAuthAlertSend": 1,
},
},
{
Name: "unknown explicit identityField",
Method: http.MethodPost,
+30 -6
View File
@@ -118,7 +118,7 @@ func recordsList(e *core.RequestEvent) error {
len(e.Records) == 0 &&
checkRateLimit(e.RequestEvent, "@pb_list_timing_check_"+collection.Id, listTimingRateLimitRule) != nil {
e.App.Logger().Debug("Randomized throttle because of too many failed searches", "collectionId", collection.Id)
randomizedThrottle(150)
randomizedThrottle(500)
}
return execAfterSuccessTx(true, e.App, func() error {
@@ -169,12 +169,18 @@ func recordView(e *core.RequestEvent) error {
ruleFunc := func(q *dbx.SelectQuery) error {
if !requestInfo.HasSuperuserAuth() && collection.ViewRule != nil && *collection.ViewRule != "" {
resolver := core.NewRecordFieldResolver(e.App, collection, requestInfo, true)
expr, err := search.FilterData(*collection.ViewRule).BuildExpr(resolver)
if err != nil {
return err
}
resolver.UpdateQuery(q)
q.AndWhere(expr)
err = resolver.UpdateQuery(q)
if err != nil {
return err
}
}
return nil
}
@@ -310,7 +316,10 @@ func recordCreate(responseWriteAfterTx bool, optFinalizer func(data any) error)
}
ruleQuery.AndWhere(expr)
resolver.UpdateQuery(ruleQuery)
err = resolver.UpdateQuery(ruleQuery)
if err != nil {
return e.BadRequestError("Failed to create record", fmt.Errorf("create rule update query failure: %w", err))
}
var exists int
err = ruleQuery.Limit(1).Row(&exists)
@@ -430,12 +439,18 @@ func recordUpdate(responseWriteAfterTx bool, optFinalizer func(data any) error)
ruleFunc := func(q *dbx.SelectQuery) error {
if !hasSuperuserAuth && collection.UpdateRule != nil && *collection.UpdateRule != "" {
resolver := core.NewRecordFieldResolver(e.App, collection, requestInfo, true)
expr, err := search.FilterData(*collection.UpdateRule).BuildExpr(resolver)
if err != nil {
return err
}
resolver.UpdateQuery(q)
q.AndWhere(expr)
err = resolver.UpdateQuery(q)
if err != nil {
return err
}
}
return nil
}
@@ -546,12 +561,18 @@ func recordDelete(responseWriteAfterTx bool, optFinalizer func(data any) error)
ruleFunc := func(q *dbx.SelectQuery) error {
if !requestInfo.HasSuperuserAuth() && collection.DeleteRule != nil && *collection.DeleteRule != "" {
resolver := core.NewRecordFieldResolver(e.App, collection, requestInfo, true)
expr, err := search.FilterData(*collection.DeleteRule).BuildExpr(resolver)
if err != nil {
return err
}
resolver.UpdateQuery(q)
q.AndWhere(expr)
err = resolver.UpdateQuery(q)
if err != nil {
return err
}
}
return nil
}
@@ -732,7 +753,10 @@ func hasAuthManageAccess(app core.App, requestInfo *core.RequestInfo, collection
}
query.AndWhere(expr)
resolver.UpdateQuery(query)
err = resolver.UpdateQuery(query)
if err != nil {
return false
}
var exists int
+30 -4
View File
@@ -382,10 +382,32 @@ func TestRecordCrudList(t *testing.T) {
},
},
{
Name: "multi-match - at least one of",
Name: "multi-match - at least one of (guest - non-satisfied relation filter API rule)",
Method: http.MethodGet,
URL: "/api/collections/demo4/records?filter=" + url.QueryEscape("rel_many_no_cascade_required.files:length?=2"),
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalPages":0`,
`"totalItems":0`,
`"items":[]`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
"OnRecordEnrich": 0,
},
},
{
Name: "multi-match - at least one of (clients)",
Method: http.MethodGet,
URL: "/api/collections/demo4/records?filter=" + url.QueryEscape("rel_many_no_cascade_required.files:length?=2"),
Headers: map[string]string{
// clients, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6ImdrMzkwcWVnczR5NDd3biIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoidjg1MXE0cjc5MHJoa25sIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.0ONnm_BsvPRZyDNT31GN1CKUB6uQRxvVvQ-Wc9AZfG0",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
@@ -401,9 +423,13 @@ func TestRecordCrudList(t *testing.T) {
},
},
{
Name: "multi-match - all",
Method: http.MethodGet,
URL: "/api/collections/demo4/records?filter=" + url.QueryEscape("rel_many_no_cascade_required.files:length=2"),
Name: "multi-match - all (clients)",
Method: http.MethodGet,
URL: "/api/collections/demo4/records?filter=" + url.QueryEscape("rel_many_no_cascade_required.files:length=2"),
Headers: map[string]string{
// clients, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6ImdrMzkwcWVnczR5NDd3biIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoidjg1MXE0cjc5MHJoa25sIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.0ONnm_BsvPRZyDNT31GN1CKUB6uQRxvVvQ-Wc9AZfG0",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
+38 -10
View File
@@ -15,6 +15,7 @@ import (
"github.com/pocketbase/pocketbase/tools/routine"
"github.com/pocketbase/pocketbase/tools/search"
"github.com/pocketbase/pocketbase/tools/security"
"github.com/pocketbase/pocketbase/tools/types"
)
const (
@@ -42,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
@@ -160,7 +168,11 @@ func wantsMFA(e *core.RequestEvent, record *core.Record) (bool, error) {
if err != nil {
return true, err
}
resolver.UpdateQuery(query)
err = resolver.UpdateQuery(query)
if err != nil {
return true, err
}
err = query.AndWhere(expr).Limit(1).Row(&exists)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
@@ -379,12 +391,18 @@ func expandFetch(app core.App, originalRequestInfo *core.RequestInfo) core.Expan
if *relCollection.ViewRule != "" {
resolver := core.NewRecordFieldResolver(app, relCollection, requestInfoPtr, true)
expr, err := search.FilterData(*(relCollection.ViewRule)).BuildExpr(resolver)
if err != nil {
return err
}
resolver.UpdateQuery(q)
q.AndWhere(expr)
err = resolver.UpdateQuery(q)
if err != nil {
return err
}
}
return nil
@@ -465,10 +483,16 @@ func autoResolveRecordsFlags(app core.App, records []*core.Record, requestInfo *
if err != nil {
return err
}
resolver.UpdateQuery(query)
query.AndWhere(expr)
if err := query.Column(&managedIds); err != nil {
err = resolver.UpdateQuery(query)
if err != nil {
return err
}
err = query.Column(&managedIds)
if err != nil {
return err
}
// ---
@@ -537,7 +561,7 @@ func firstApiError(errs ...error) *router.ApiError {
return router.NewInternalServerError("", errors.Join(errs...))
}
// execAfterSuccessTx ensures that fn is executed only after a succesul transaction.
// execAfterSuccessTx ensures that fn is executed only after a successful transaction.
//
// If the current app instance is not a transactional or checkTx is false,
// then fn is directly executed.
@@ -563,13 +587,17 @@ func execAfterSuccessTx(checkTx bool, app core.App, fn func() error) error {
const maxAuthOrigins = 5
func authAlert(e *core.RequestEvent, authRecord *core.Record) error {
// generating fingerprint
// generate fingerprint
// ---
ip := e.RealIP()
userAgent := e.Request.UserAgent()
if len(userAgent) > 300 {
userAgent = userAgent[:300]
if len(userAgent) > 200 {
userAgent = userAgent[:200] + "..."
}
fingerprint := security.MD5(e.RealIP() + userAgent)
fingerprint := security.MD5(ip + userAgent)
alertInfo := fmt.Sprintf("%s - %s %s", types.NowDateTime().String(), ip, userAgent)
// ---
origins, err := e.App.FindAllAuthOriginsByRecord(authRecord)
@@ -609,7 +637,7 @@ func authAlert(e *core.RequestEvent, authRecord *core.Record) error {
})
routine.FireAndForget(func() {
err := mails.SendRecordAuthAlert(e.App, authRecord)
err := mails.SendRecordAuthAlert(e.App, authRecord, alertInfo)
timer.Stop()
mailSent <- err
})
+37 -1
View File
@@ -1,7 +1,7 @@
package apis_test
import (
"encoding/json"
"encoding/json/v2"
"errors"
"net/http"
"net/http/httptest"
@@ -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)
}
})
}
+25 -15
View File
@@ -22,6 +22,8 @@ import (
"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-ancestors 'none'"
// ServeConfig defines a configuration struct for apis.Serve().
type ServeConfig struct {
// ShowStartBanner indicates whether to show or hide the server start console message.
@@ -77,21 +79,25 @@ func Serve(app core.App, config ServeConfig) error {
AllowMethods: []string{http.MethodGet, http.MethodHead, http.MethodPut, http.MethodPatch, http.MethodPost, http.MethodDelete},
}))
pbRouter.GET("/_/{path...}", Static(ui.DistDirFS, false)).
BindFunc(func(e *core.RequestEvent) error {
// ignore root path
if e.Request.PathValue(StaticWildcardParam) != "" {
e.Response.Header().Set("Cache-Control", "max-age=1209600, stale-while-revalidate=86400")
}
// @todo consider moving in base
if ui.DistDirFS != nil {
pbRouter.GET("/_/{path...}", Static(ui.DistDirFS, false)).
BindFunc(func(e *core.RequestEvent) error {
if !e.App.IsDev() &&
// exclude root path
e.Request.PathValue(StaticWildcardParam) != "" &&
e.Response.Header().Get("Cache-Control") == "" {
e.Response.Header().Set("Cache-Control", "max-age=1209600, stale-while-revalidate=86400")
}
// add a default CSP
if e.Response.Header().Get("Content-Security-Policy") == "" {
e.Response.Header().Set("Content-Security-Policy", "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' 'sha256-GRUzBA7PzKYug7pqxv5rJaec5bwDCw1Vo6/IXwvD3Tc='")
}
if e.Response.Header().Get("Content-Security-Policy") == "" {
e.Response.Header().Set("Content-Security-Policy", defaultCSP)
}
return e.Next()
}).
Bind(Gzip())
return e.Next()
}).
Bind(Gzip())
}
// start http server
// ---
@@ -279,8 +285,12 @@ func Serve(app core.App, config ServeConfig) error {
)
regular := color.New()
regular.Printf("├─ REST API: %s\n", color.CyanString("%s/api/", baseURL))
regular.Printf("└─ Dashboard: %s\n", color.CyanString("%s/_/", baseURL))
if ui.DistDirFS == nil {
regular.Printf("└─ REST API: %s\n", color.CyanString("%s/api/", baseURL))
} else {
regular.Printf("├─ REST API: %s\n", color.CyanString("%s/api/", baseURL))
regular.Printf("└─ Dashboard: %s\n", color.CyanString("%s/_/", baseURL))
}
}
var serveErr error
+8 -6
View File
@@ -3,7 +3,7 @@ package apis
import (
"net/http"
validation "github.com/go-ozzo/ozzo-validation/v4"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/forms"
"github.com/pocketbase/pocketbase/tools/router"
@@ -16,6 +16,8 @@ func bindSettingsApi(app core.App, rg *router.RouterGroup[*core.RequestEvent]) {
subGroup.PATCH("", settingsSet)
subGroup.POST("/test/s3", settingsTestS3)
subGroup.POST("/test/email", settingsTestEmail)
// @todo move to collections
subGroup.POST("/apple/generate-client-secret", settingsGenerateAppleClientSecret)
}
@@ -62,12 +64,12 @@ func settingsSet(e *core.RequestEvent) error {
return e.BadRequestError("An error occurred while saving the new settings.", err)
}
appSettings, err := e.App.Settings().Clone()
if err != nil {
return e.InternalServerError("Failed to clone app settings.", err)
}
return execAfterSuccessTx(true, e.App, func() error {
appSettings, err := e.App.Settings().Clone()
if err != nil {
return e.InternalServerError("Failed to clone app settings.", err)
}
return e.JSON(http.StatusOK, appSettings)
})
})
+22 -2
View File
@@ -97,8 +97,9 @@ func TestSettingsSet(t *testing.T) {
validData := `{
"meta":{"appName":"update_test"},
"s3":{"secret": "s3_secret"},
"backups":{"s3":{"secret":"backups_s3_secret"}}
"smtp":{"password": "new_smtp_password"},
"s3":{"secret": "new_s3_secret"},
"backups":{"s3":{"secret":"new_backups_s3_secret"}}
}`
scenarios := []tests.ApiScenario{
@@ -179,6 +180,25 @@ func TestSettingsSet(t *testing.T) {
Headers: map[string]string{
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InN5d2JoZWNuaDQ2cmhtMCIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoicGJjXzMxNDI2MzU4MjMiLCJleHAiOjI1MjQ2MDQ0NjEsInJlZnJlc2hhYmxlIjp0cnVlfQ.UXgO3j-0BumcugrFjbd7j0M4MQvbrLggLlcu_YNGjoY",
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
settings := app.Settings()
// verify that the secret values are persisted
secrets := map[string]struct {
current string
expected string
}{
"smtp.password": {settings.SMTP.Password, "new_smtp_password"},
"s3.secret": {settings.S3.Secret, "new_s3_secret"},
"backups.s3.secret": {settings.Backups.S3.Secret, "new_backups_s3_secret"},
}
for name, secret := range secrets {
if secret.current != secret.expected {
t.Errorf("[%s] expected secret %q, got %q", name, secret.expected, secret.current)
}
}
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"meta":{`,
+194
View File
@@ -0,0 +1,194 @@
package apis
import (
"context"
"errors"
"log/slog"
"net/http"
"strings"
"time"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/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
}
+220
View File
@@ -0,0 +1,220 @@
package apis_test
import (
"net/http"
"strings"
"testing"
"github.com/pocketbase/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)
}
}
+37 -1
View File
@@ -5,7 +5,7 @@ import (
"fmt"
"github.com/fatih/color"
"github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/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
}
+61
View File
@@ -1,6 +1,7 @@
package cmd_test
import (
"slices"
"testing"
"github.com/pocketbase/pocketbase/cmd"
@@ -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)
}
}
})
}
}
+40 -9
View File
@@ -240,29 +240,41 @@ type App interface {
// This method is a no-op if a table with the provided name doesn't exist.
//
// NB! Be aware that this method is vulnerable to SQL injection and the
// "tableName" argument must come only from trusted input!
DeleteTable(tableName string) error
// "dangerousTableName" argument must come only from trusted input!
DeleteTable(dangerousTableName string) error
// DeleteView drops the specified view name.
//
// This method is a no-op if a view with the provided name doesn't exist.
//
// NB! Be aware that this method is vulnerable to SQL injection and the
// "name" argument must come only from trusted input!
DeleteView(name string) error
// "dangerousViewName" argument must come only from trusted input!
DeleteView(dangerousViewName string) error
// SaveView creates (or updates already existing) persistent SQL view.
//
// NB! Be aware that this method is vulnerable to SQL injection and the
// "selectQuery" argument must come only from trusted input!
SaveView(name string, selectQuery string) error
// NB! Be aware that this method is vulnerable to SQL injection and
// its arguments must come only from trusted input!
SaveView(dangerousViewName string, dangerousSelectQuery string) error
// CreateViewFields creates a new FieldsList from the provided select query.
//
// There are some caveats:
// - The select query must have an "id" column.
// - Wildcard ("*") columns are not supported to avoid accidentally leaking sensitive data.
CreateViewFields(selectQuery string) (FieldsList, error)
//
// NB! Be aware that this method is vulnerable to SQL injection and the
// "dangerousSelectQuery" argument must come only from trusted input!
CreateViewFields(dangerousSelectQuery string) (FieldsList, error)
// DryRunView executes the provided query by creating a temporary view
// collection and returning a sample of the resulting query records (if valid).
//
// The same caveats from CreateViewFields apply here too.
//
// NB! Be aware that this method is vulnerable to SQL injection and the
// "dangerousSelectQuery" argument must come only from trusted input!
DryRunView(dangerousSelectQuery string, sampleSize int) (*DryRunViewResult, error)
// FindRecordByViewFile returns the original Record of the provided view collection file.
FindRecordByViewFile(viewCollectionModelOrIdentifier any, fileFieldName string, filename string) (*Record, error)
@@ -490,6 +502,11 @@ type App interface {
// ExternalAuth model that satisfies the non-nil expression.
FindFirstExternalAuthByExpr(expr dbx.Expression) (*ExternalAuth, error)
// DeleteAllExternalAuthsByRecord deletes all ExternalAuth models associated with the provided record.
//
// Returns a combined error with the failed deletes.
DeleteAllExternalAuthsByRecord(authRecord *Record) error
// ---------------------------------------------------------------
// FindAllMFAsByRecord returns all MFA models linked to the provided auth record.
@@ -1195,7 +1212,7 @@ type App interface {
// ---------------------------------------------------------------
// OnMailerSend hook is triggered every time when a new email is
// being send using the [App.NewMailClient()] instance.
// being sent using the [App.NewMailClient()] instance.
//
// It allows intercepting the email message or to use a custom mailer client.
OnMailerSend() *hook.Hook[*MailerEvent]
@@ -1245,6 +1262,20 @@ type App interface {
// triggered and called only if their event data origin matches the tags.
OnMailerRecordOTPSend(tags ...string) *hook.TaggedHook[*MailerRecordEvent]
// ---------------------------------------------------------------
// Filesystem event hooks
// (not publicly exposed until file_field refactoring)
// ---------------------------------------------------------------
// onFilesystemNewWriter is an internal hook for app.NewFilesystem()
// instances that is triggered on every storage filesystem writer initialization
// (aka. whenever attempting to create a new file).
onFilesystemNewWriter() *hook.Hook[*FilesystemNewWriterEvent]
// onFilesystemDelete is an internal hook for app.NewFilesystem()
// instances that is triggered for every storage file delete call.
onFilesystemDelete() *hook.Hook[*FilesystemDeleteEvent]
// ---------------------------------------------------------------
// Realtime API event hooks
// ---------------------------------------------------------------
+1 -1
View File
@@ -5,8 +5,8 @@ import (
"errors"
"slices"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/dbx"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/types"
)
+137
View File
@@ -0,0 +1,137 @@
package core
import (
"context"
"fmt"
"log/slog"
"sort"
"time"
"github.com/pocketbase/pocketbase/tools/inflector"
)
const (
StoreKeyActiveBackup = "@activeBackup"
)
// generateBackupName generates a new backup name based on the app name and current date.
func generateBackupName(app App, prefix string) string {
appName := inflector.Snakecase(app.Settings().Meta.AppName)
if len(appName) > 50 {
appName = appName[:50]
}
return fmt.Sprintf(
"%s%s_%s.zip",
prefix,
appName,
time.Now().UTC().Format("20060102150405"),
)
}
// registerAutobackupHooks registers the autobackup app serve hooks.
func (app *BaseApp) registerAutobackupHooks() {
const jobId = "__pbAutoBackup__"
loadJob := func() {
rawSchedule := app.Settings().Backups.Cron
if rawSchedule == "" {
app.Cron().Remove(jobId)
return
}
app.Cron().Add(jobId, rawSchedule, func() {
const autoPrefix = "@auto_pb_backup_"
name := generateBackupName(app, autoPrefix)
if err := app.CreateBackup(context.Background(), name); err != nil {
app.Logger().Error(
"[Backup cron] Failed to create backup",
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
if maxKeep == 0 {
return // no explicit limit
}
fsys, err := app.NewBackupsFilesystem()
if err != nil {
app.Logger().Error(
"[Backup cron] Failed to initialize the backup filesystem",
slog.String("error", err.Error()),
)
return
}
defer fsys.Close()
files, err := fsys.List(autoPrefix)
if err != nil {
app.Logger().Error(
"[Backup cron] Failed to list autogenerated backups",
slog.String("error", err.Error()),
)
return
}
if maxKeep >= len(files) {
return // nothing to remove
}
// sort desc
sort.Slice(files, func(i, j int) bool {
return files[i].ModTime.After(files[j].ModTime)
})
// keep only the most recent n auto backup files
toRemove := files[maxKeep:]
for _, f := range toRemove {
if err := fsys.Delete(f.Key); err != nil {
app.Logger().Error(
"[Backup cron] Failed to remove old autogenerated backup",
slog.String("key", f.Key),
slog.String("error", err.Error()),
)
}
}
})
}
app.OnBootstrap().BindFunc(func(e *BootstrapEvent) error {
if err := e.Next(); err != nil {
return err
}
loadJob()
return nil
})
app.OnSettingsReload().BindFunc(func(e *SettingsReloadEvent) error {
if err := e.Next(); err != nil {
return err
}
loadJob()
return nil
})
}
+437
View File
@@ -0,0 +1,437 @@
package core
import (
"archive/zip"
"compress/flate"
"context"
"errors"
"fmt"
"io"
"io/fs"
"log/slog"
"os"
"path"
"path/filepath"
"strings"
"sync"
"time"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/filesystem"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/security"
"github.com/pocketbase/pocketbase/tools/store"
)
var errIsDir = errors.New("the specified path is a directory and not a regular file")
// CreateBackup creates a new backup of the current app pb_data directory.
//
// If name is empty, it will be autogenerated.
// If backup with the same name exists, the new backup file will replace it.
//
// To safely perform the backup, it is recommended to have free disk space
// for at least 2x the size of the pb_data directory.
//
// By default backups are stored in pb_data/backups
// (the backups directory itself is excluded from the generated backup).
//
// Backups can be stored on S3 if it is configured in app.Settings().Backups.
// When using S3 storage for the uploaded collection files, you have to
// take care manually to backup those since they are not part of the pb_data.
//
// DB write locks are minimal and isolated only for the duration of the
// VACUUM INTO statement that creates a live copy of the app database.
//
// The backup works as follow:
//
// 1. Start listening for DELETED storage files.
// In case a file is being deleted while the backup is still ongoing,
// we directly copy it in the zip before the deletion and mark it as "excluded".
//
// 2. Copy the main database with VACUUM INTO, write it in the zip and mark it as "excluded".
//
// 3. Stop listening for DELETED files.
//
// 4. Start listening for NEW storage files and mark all new files from this point as "excluded".
//
// 5. Copy the logs database with VACUUM INTO, write it in the zip and mark it as "excluded".
//
// 6. Copy the rest of the pb_data files in the zip while ignoring the "excluded" list (it should be concurrent safe).
//
// 7. Stop listening for NEW storage files.
//
// While there is a risk for a race condition between steps 1, 2 and 3, it is an
// acceptable trade-off between performance and correctness because in
// the worst case there will be some unused storage files in the backup that don't do any harm.
func (app *BaseApp) CreateBackup(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")
}
app.Store().Set(StoreKeyActiveBackup, name)
defer app.Store().Remove(StoreKeyActiveBackup)
startTime := time.Now()
event := new(BackupEvent)
event.App = app
event.Context = ctx
event.Name = name
// default root dir entries to exclude from the backup generation
event.Exclude = []string{
LocalBackupsDirName,
LocalTempDirName,
LocalNotifyDirName,
LocalAutocertCacheDirName,
lostFoundDirName,
}
return app.OnBackupCreate().Trigger(event, func(e *BackupEvent) error {
if e.Name == "" {
e.Name = generateBackupName(e.App, "pb_backup_")
}
app.Logger().Debug("[" + e.Name + "] zip archive started")
// create backup zip
// (it needs to be inside the current pb_data to avoid "cross-device link" errors)
// -----------------------------------------------------------
tempZipPath := filepath.Join(app.DataDir(), LocalTempDirName, "pb_backup_"+security.PseudorandomString(6))
err := createZip(e, tempZipPath)
if err != nil {
return err
}
defer os.Remove(tempZipPath)
// persist the backup in the backups filesystem
// -----------------------------------------------------------
fsys, err := e.App.NewBackupsFilesystem()
if err != nil {
return err
}
defer fsys.Close()
fsys.SetContext(e.Context)
file, err := filesystem.NewFileFromPath(tempZipPath)
if err != nil {
return err
}
file.OriginalName = e.Name
file.Name = file.OriginalName
err = fsys.UploadFile(file, file.Name)
if err != nil {
return err
}
app.Logger().Debug(
"["+e.Name+"] zip archive completed",
slog.Float64("execTime", float64(time.Since(startTime))/float64(time.Millisecond)),
)
return nil
})
}
func createZip(be *BackupEvent, tempZipPath string) error {
logPrefix := "[" + be.Name + "] "
// make sure that the special temp directory exists
localTempDir := filepath.Dir(tempZipPath)
if err := os.MkdirAll(localTempDir, os.ModePerm); err != nil {
return fmt.Errorf(logPrefix+"failed to create temp dir: %w", err)
}
const tempFilesHookId = "__pbTempBackupFilesystemWatcher__"
defer func() {
// unbind again in cacase of an error
be.App.onFilesystemDelete().Unbind(tempFilesHookId)
be.App.onFilesystemNewWriter().Unbind(tempFilesHookId)
}()
zipper, err := newZipWriter(tempZipPath)
if err != nil {
return err
}
defer zipper.close()
excluded := store.New[string, struct{}](nil)
for _, name := range be.Exclude {
excluded.Set(normalizePathExclude(name), struct{}{})
}
// init deleted files tracker
// ---------------------------------------------------------------
be.App.onFilesystemDelete().Bind(&hook.Handler[*FilesystemDeleteEvent]{
Id: tempFilesHookId,
Priority: -99,
Func: func(e *FilesystemDeleteEvent) error {
// note: the zip header name allow only forward slashes
zipPath := path.Join(LocalStorageDirName, e.FileKey)
if excluded.Has(normalizePathExclude(zipPath)) || be.App.Settings().S3.Enabled {
return e.Next()
}
localPath := filepath.Join(
be.App.DataDir(),
LocalStorageDirName,
e.FileKey,
)
// copy to zip before delete
err := zipper.copyFileToZip(localPath, zipPath)
if err != nil {
// it is ok to ignore directories
if !errors.Is(err, errIsDir) {
be.App.Logger().Warn(
logPrefix+"failed to copy file in backup zip before delete",
slog.Any("error", err),
slog.String("file", e.FileKey),
)
}
} else {
// mark that it was already copied
excluded.Set(normalizePathExclude(zipPath), struct{}{})
}
// proceed with the normal deletion
return e.Next()
},
})
// copy data.db
// ---------------------------------------------------------------
dataStartTime := time.Now()
tempDataDBPath := filepath.Join(localTempDir, dataDBFilename)
_, err = be.App.ConcurrentDB().NewQuery("VACUUM INTO {:path}").Bind(dbx.Params{"path": tempDataDBPath}).Execute()
if err != nil {
return err
}
// eagerly stop listening for deleted files since we already have what we needed
be.App.onFilesystemDelete().Unbind(tempFilesHookId)
be.App.Logger().Debug(
logPrefix+dataDBFilename+" copy completed",
slog.Float64("execTime", float64(time.Since(dataStartTime))/float64(time.Millisecond)),
)
err = zipper.copyFileToZip(tempDataDBPath, dataDBFilename)
if err != nil {
_ = os.Remove(tempDataDBPath)
return err
}
_ = os.Remove(tempDataDBPath)
excluded.Set(normalizePathExclude(dataDBFilename), struct{}{})
excluded.Set(normalizePathExclude(dataDBFilename+"-wal"), struct{}{})
excluded.Set(normalizePathExclude(dataDBFilename+"-shm"), struct{}{})
// init to-be-created files tracker
// ---------------------------------------------------------------
be.App.onFilesystemNewWriter().Bind(&hook.Handler[*FilesystemNewWriterEvent]{
Id: tempFilesHookId,
Priority: -99,
Func: func(e *FilesystemNewWriterEvent) error {
if !be.App.Settings().S3.Enabled {
// mark for exclude even if the writer eventually fails
// (all record files have random name so collisions are unlikely)
name := normalizePathExclude(filepath.Join(LocalStorageDirName, e.FileKey))
excluded.Set(name, struct{}{})
}
return e.Next()
},
})
// copy auxiliary.db
// ---------------------------------------------------------------
auxStartTime := time.Now()
tempAuxDBPath := filepath.Join(localTempDir, auxDBFilename)
_, err = be.App.AuxConcurrentDB().NewQuery("VACUUM INTO {:path}").Bind(dbx.Params{"path": tempAuxDBPath}).Execute()
if err != nil {
return err
}
be.App.Logger().Debug(
logPrefix+auxDBFilename+" copy completed",
slog.Float64("execTime", float64(time.Since(auxStartTime))/float64(time.Millisecond)),
)
err = zipper.copyFileToZip(tempAuxDBPath, auxDBFilename)
if err != nil {
_ = os.Remove(tempAuxDBPath)
return err
}
_ = os.Remove(tempAuxDBPath)
excluded.Set(normalizePathExclude(auxDBFilename), struct{}{})
excluded.Set(normalizePathExclude(auxDBFilename+"-wal"), struct{}{})
excluded.Set(normalizePathExclude(auxDBFilename+"-shm"), struct{}{})
// try to run manual checkpoints to ensure that all wal writes during the
// previous VACUUM INTO are transferred and don't accumulate
// (errors are ignore because some drivers may not support the wal_checkpoint pragma)
// ---------------------------------------------------------------
_, _ = be.App.NonconcurrentDB().NewQuery("PRAGMA wal_checkpoint(TRUNCATE)").Execute()
_, _ = be.App.AuxNonconcurrentDB().NewQuery("PRAGMA wal_checkpoint(TRUNCATE)").Execute()
// copy the rest of the pb_data
// ---------------------------------------------------------------
err = zipper.copyDirToZip(os.DirFS(be.App.DataDir()), excluded)
if err != nil {
return err
}
return zipper.close()
}
// normalize the provided file path to always end with forward slash
func normalizePathExclude(filePath string) string {
return path.Clean(filePath) + "/"
}
type zipWriter struct {
mu sync.Mutex
w *zip.Writer
f *os.File
closed bool
}
func newZipWriter(zipFilePath string) (*zipWriter, error) {
f, err := os.Create(zipFilePath)
if err != nil {
return nil, err
}
w := zip.NewWriter(f)
w.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) {
return flate.NewWriter(out, flate.BestSpeed)
})
return &zipWriter{
w: w,
f: f,
}, nil
}
func (z *zipWriter) close() error {
z.mu.Lock()
defer z.mu.Unlock()
if z.closed {
return nil
}
z.closed = true
return errors.Join(z.w.Close(), z.f.Close())
}
func (z *zipWriter) copyFileToZip(localPath string, zipPath string) error {
info, err := os.Stat(localPath)
if err != nil {
return err
}
if info.IsDir() {
return errIsDir
}
h, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
h.Name = zipPath
h.Method = zip.Deflate
z.mu.Lock()
defer z.mu.Unlock()
if z.closed {
return errors.New("zip writer is already closed")
}
fw, err := z.w.CreateHeader(h)
if err != nil {
return err
}
f, err := os.Open(localPath)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(fw, f)
return err
}
func (z *zipWriter) copyDirToZip(fsys fs.FS, excludedPrefixes *store.Store[string, struct{}]) error {
return fs.WalkDir(fsys, ".", func(name string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
// skip excluded prefixes
if excludedPrefixes != nil {
check := normalizePathExclude(name)
prefixes := excludedPrefixes.Keys() // refetch to avoid races
for _, prefix := range prefixes {
if strings.HasPrefix(check, prefix) {
if d.IsDir() {
return fs.SkipDir
}
return nil
}
}
}
if d.IsDir() {
return nil
}
info, err := d.Info()
if err != nil {
return err
}
h, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
h.Name = name
h.Method = zip.Deflate
z.mu.Lock()
defer z.mu.Unlock()
if z.closed {
// note: fs.WalkDir perform direct comparison with the value
return fs.SkipAll
}
fw, err := z.w.CreateHeader(h)
if err != nil {
return err
}
f, err := fsys.Open(name)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(fw, f)
return err
})
}
+2 -209
View File
@@ -9,111 +9,12 @@ import (
"os"
"path/filepath"
"runtime"
"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"
)
const (
StoreKeyActiveBackup = "@activeBackup"
)
// CreateBackup creates a new backup of the current app pb_data directory.
//
// If name is empty, it will be autogenerated.
// If backup with the same name exists, the new backup file will replace it.
//
// The backup is executed within a transaction, meaning that new writes
// will be temporary "blocked" until the backup file is generated.
//
// To safely perform the backup, it is recommended to have free disk space
// for at least 2x the size of the pb_data directory.
//
// By default backups are stored in pb_data/backups
// (the backups directory itself is excluded from the generated backup).
//
// When using S3 storage for the uploaded collection files, you have to
// take care manually to backup those since they are not part of the pb_data.
//
// Backups can be stored on S3 if it is configured in app.Settings().Backups.
func (app *BaseApp) CreateBackup(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")
}
app.Store().Set(StoreKeyActiveBackup, name)
defer app.Store().Remove(StoreKeyActiveBackup)
event := new(BackupEvent)
event.App = app
event.Context = ctx
event.Name = name
// default root dir entries to exclude from the backup generation
event.Exclude = []string{LocalBackupsDirName, LocalTempDirName, LocalAutocertCacheDirName, lostFoundDirName}
return app.OnBackupCreate().Trigger(event, func(e *BackupEvent) error {
// generate a default name if missing
if e.Name == "" {
e.Name = generateBackupName(e.App, "pb_backup_")
}
// make sure that the special temp directory exists
// note: it needs to be inside the current pb_data to avoid "cross-device link" errors
localTempDir := filepath.Join(e.App.DataDir(), LocalTempDirName)
if err := os.MkdirAll(localTempDir, os.ModePerm); err != nil {
return fmt.Errorf("failed to create a temp dir: %w", err)
}
// archive pb_data in a temp directory, exluding the "backups" and the temp dirs
//
// run in transaction to temporary block other writes (transactions uses the NonconcurrentDB connection)
// ---
tempPath := filepath.Join(localTempDir, "pb_backup_"+security.PseudorandomString(6))
createErr := e.App.RunInTransaction(func(txApp App) error {
return txApp.AuxRunInTransaction(func(txApp App) error {
// run manual checkpoint and truncate the WAL files
// (errors are ignored because it is not that important and the PRAGMA may not be supported by the used driver)
txApp.DB().NewQuery("PRAGMA wal_checkpoint(TRUNCATE)").Execute()
txApp.AuxDB().NewQuery("PRAGMA wal_checkpoint(TRUNCATE)").Execute()
return archive.Create(txApp.DataDir(), tempPath, e.Exclude...)
})
})
if createErr != nil {
return createErr
}
defer os.Remove(tempPath)
// persist the backup in the backups filesystem
// ---
fsys, err := e.App.NewBackupsFilesystem()
if err != nil {
return err
}
defer fsys.Close()
fsys.SetContext(e.Context)
file, err := filesystem.NewFileFromPath(tempPath)
if err != nil {
return err
}
file.OriginalName = e.Name
file.Name = file.OriginalName
if err := fsys.UploadFile(file, file.Name); err != nil {
return err
}
return nil
})
}
// RestoreBackup restores the backup with the specified name and restarts
// the current running application process.
//
@@ -138,9 +39,9 @@ func (app *BaseApp) CreateBackup(ctx context.Context, name string) error {
//
// 4. Move the extracted dir content to the app "pb_data".
//
// 5. Restart the app (on successful app bootstap it will also remove the old pb_data).
// 5. Restart the app (on successful app bootstrap it will also remove the old pb_data).
//
// If a failure occure during the restore process the dir changes are reverted.
// If a failure occur during the restore process the dir changes are reverted.
// If for whatever reason the revert is not possible, it panics.
//
// Note that if your pb_data has custom network mounts as subdirectories, then
@@ -293,111 +194,3 @@ func (app *BaseApp) RestoreBackup(ctx context.Context, name string) error {
return nil
})
}
// registerAutobackupHooks registers the autobackup app serve hooks.
func (app *BaseApp) registerAutobackupHooks() {
const jobId = "__pbAutoBackup__"
loadJob := func() {
rawSchedule := app.Settings().Backups.Cron
if rawSchedule == "" {
app.Cron().Remove(jobId)
return
}
app.Cron().Add(jobId, rawSchedule, func() {
const autoPrefix = "@auto_pb_backup_"
name := generateBackupName(app, autoPrefix)
if err := app.CreateBackup(context.Background(), name); err != nil {
app.Logger().Error(
"[Backup cron] Failed to create backup",
slog.String("name", name),
slog.String("error", err.Error()),
)
}
maxKeep := app.Settings().Backups.CronMaxKeep
if maxKeep == 0 {
return // no explicit limit
}
fsys, err := app.NewBackupsFilesystem()
if err != nil {
app.Logger().Error(
"[Backup cron] Failed to initialize the backup filesystem",
slog.String("error", err.Error()),
)
return
}
defer fsys.Close()
files, err := fsys.List(autoPrefix)
if err != nil {
app.Logger().Error(
"[Backup cron] Failed to list autogenerated backups",
slog.String("error", err.Error()),
)
return
}
if maxKeep >= len(files) {
return // nothing to remove
}
// sort desc
sort.Slice(files, func(i, j int) bool {
return files[i].ModTime.After(files[j].ModTime)
})
// keep only the most recent n auto backup files
toRemove := files[maxKeep:]
for _, f := range toRemove {
if err := fsys.Delete(f.Key); err != nil {
app.Logger().Error(
"[Backup cron] Failed to remove old autogenerated backup",
slog.String("key", f.Key),
slog.String("error", err.Error()),
)
}
}
})
}
app.OnBootstrap().BindFunc(func(e *BootstrapEvent) error {
if err := e.Next(); err != nil {
return err
}
loadJob()
return nil
})
app.OnSettingsReload().BindFunc(func(e *SettingsReloadEvent) error {
if err := e.Next(); err != nil {
return err
}
loadJob()
return nil
})
}
func generateBackupName(app App, prefix string) string {
appName := inflector.Snakecase(app.Settings().Meta.AppName)
if len(appName) > 50 {
appName = appName[:50]
}
return fmt.Sprintf(
"%s%s_%s.zip",
prefix,
appName,
time.Now().UTC().Format("20060102150405"),
)
}
@@ -126,11 +126,7 @@ func verifyBackupContent(app core.App, path string) error {
expectedRootEntries := []string{
"storage",
"data.db",
"data.db-shm",
"data.db-wal",
"auxiliary.db",
"auxiliary.db-shm",
"auxiliary.db-wal",
".gitignore",
}
+80 -12
View File
@@ -38,11 +38,15 @@ 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"
dataDBFilename string = "data.db"
auxDBFilename string = "auxiliary.db"
)
// FilesManager defines an interface with common methods that files manager models should implement.
@@ -145,6 +149,17 @@ type BaseApp struct {
onMailerRecordOTPSend *hook.Hook[*MailerRecordEvent]
onMailerRecordAuthAlertSend *hook.Hook[*MailerRecordEvent]
// filesystem event hooks
//
// @todo 1:
// intentionally not exposed since the events are too "chatty" and
// can cause unnecessary userland tests breaking changes;
// reevaluate once refactoring the file_field
//
// @todo 2: if exposed consider registering the same for the backup filesystem
_onFilesystemNewWriter *hook.Hook[*FilesystemNewWriterEvent]
_onFilesystemDelete *hook.Hook[*FilesystemDeleteEvent]
// realtime api event hooks
onRealtimeConnectRequest *hook.Hook[*RealtimeConnectRequestEvent]
onRealtimeMessageSend *hook.Hook[*RealtimeMessageEvent]
@@ -293,6 +308,10 @@ func (app *BaseApp) initHooks() {
app.onMailerRecordOTPSend = &hook.Hook[*MailerRecordEvent]{}
app.onMailerRecordAuthAlertSend = &hook.Hook[*MailerRecordEvent]{}
// filesystem event hooks
app._onFilesystemNewWriter = &hook.Hook[*FilesystemNewWriterEvent]{}
app._onFilesystemDelete = &hook.Hook[*FilesystemDeleteEvent]{}
// realtime API event hooks
app.onRealtimeConnectRequest = &hook.Hook[*RealtimeConnectRequestEvent]{}
app.onRealtimeMessageSend = &hook.Hook[*RealtimeMessageEvent]{}
@@ -711,9 +730,10 @@ func (app *BaseApp) NewMailClient() mailer.Mailer {
//
// NB! Make sure to call Close() on the returned result
// after you are done working with it.
func (app *BaseApp) NewFilesystem() (*filesystem.System, error) {
func (app *BaseApp) NewFilesystem() (fsys *filesystem.System, err error) {
if app.settings != nil && app.settings.S3.Enabled {
return filesystem.NewS3(
// S3
fsys, err = filesystem.NewS3(
app.settings.S3.Bucket,
app.settings.S3.Region,
app.settings.S3.Endpoint,
@@ -721,10 +741,41 @@ func (app *BaseApp) NewFilesystem() (*filesystem.System, error) {
app.settings.S3.Secret,
app.settings.S3.ForcePathStyle,
)
} else {
// local filesystem
fsys, err = filesystem.NewLocal(filepath.Join(app.DataDir(), LocalStorageDirName))
}
if err != nil {
return nil, err
}
// fallback to local filesystem
return filesystem.NewLocal(filepath.Join(app.DataDir(), LocalStorageDirName))
// attach delete hook
if app._onFilesystemDelete.Length() > 0 {
fsys.OnDelete().BindFunc(func(originalEvent *filesystem.DeleteEvent) error {
appEvent := new(FilesystemDeleteEvent)
appEvent.DeleteEvent = originalEvent
appEvent.App = app
return app._onFilesystemDelete.Trigger(appEvent, func(fde *FilesystemDeleteEvent) error {
return originalEvent.Next()
})
})
}
// attach write hook
if app._onFilesystemNewWriter.Length() > 0 {
fsys.OnNewWriter().BindFunc(func(originalEvent *filesystem.NewWriterEvent) error {
appEvent := new(FilesystemNewWriterEvent)
appEvent.NewWriterEvent = originalEvent
appEvent.App = app
return app._onFilesystemNewWriter.Trigger(appEvent, func(fwe *FilesystemNewWriterEvent) error {
return originalEvent.Next()
})
})
}
return fsys, nil
}
// NewBackupsFilesystem creates a new local or S3 filesystem instance
@@ -1015,6 +1066,18 @@ func (app *BaseApp) OnMailerRecordAuthAlertSend(tags ...string) *hook.TaggedHook
return hook.NewTaggedHook(app.onMailerRecordAuthAlertSend, tags...)
}
// -------------------------------------------------------------------
// Filesystem event hooks
// -------------------------------------------------------------------
func (app *BaseApp) onFilesystemNewWriter() *hook.Hook[*FilesystemNewWriterEvent] {
return app._onFilesystemNewWriter
}
func (app *BaseApp) onFilesystemDelete() *hook.Hook[*FilesystemDeleteEvent] {
return app._onFilesystemDelete
}
// -------------------------------------------------------------------
// Realtime API event hooks
// -------------------------------------------------------------------
@@ -1172,7 +1235,7 @@ func (app *BaseApp) OnBatchRequest() *hook.Hook[*BatchRequestEvent] {
// -------------------------------------------------------------------
func (app *BaseApp) initDataDB() error {
dbPath := filepath.Join(app.DataDir(), "data.db")
dbPath := filepath.Join(app.DataDir(), dataDBFilename)
concurrentDB, err := app.config.DBConnect(dbPath)
if err != nil {
@@ -1220,7 +1283,7 @@ var sqlLogReplacements = []struct {
{regexp.MustCompile(`<nil>`), "NULL"},
}
// normalizeSQLLog replaces common query builder charactes with their plain SQL version for easier debugging.
// normalizeSQLLog replaces common query builder characters with their plain SQL version for easier debugging.
// The query is still not suitable for execution and should be used only for log and debug purposes
// (the normalization is done here to avoid breaking changes in dbx).
func normalizeSQLLog(sql string) string {
@@ -1234,7 +1297,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)
dbPath := filepath.Join(app.DataDir(), "auxiliary.db")
dbPath := filepath.Join(app.DataDir(), auxDBFilename)
concurrentDB, err := app.config.DBConnect(dbPath)
if err != nil {
@@ -1382,6 +1445,7 @@ func (app *BaseApp) registerBaseHooks() {
app.registerMFAHooks()
app.registerOTPHooks()
app.registerAuthOriginHooks()
app.registerNotifyWatcherHooks()
}
// getLoggerMinLevel returns the logger min level based on the
@@ -1408,7 +1472,7 @@ func getLoggerMinLevel(app App) slog.Level {
func (app *BaseApp) initLogger() error {
duration := 3 * time.Second
ticker := time.NewTicker(duration)
done := make(chan bool)
done := make(chan bool, 1)
handler := logger.NewBatchHandler(logger.BatchOptions{
Level: getLoggerMinLevel(app),
@@ -1456,7 +1520,7 @@ func (app *BaseApp) initLogger() error {
},
})
go func() {
routine.FireAndForget(func() {
ctx := context.Background()
for {
@@ -1467,7 +1531,7 @@ func (app *BaseApp) initLogger() error {
handler.WriteAll(ctx)
}
}
}()
})
app.logger = slog.New(handler)
@@ -1479,7 +1543,11 @@ func (app *BaseApp) initLogger() error {
ticker.Stop()
done <- true
// don't block in case OnTerminate is triggered more than once
select {
case done <- true:
default:
}
return e.Next()
},
+39 -19
View File
@@ -7,6 +7,7 @@ import (
"os"
"slices"
"testing"
"testing/synctest"
"time"
_ "unsafe"
@@ -302,31 +303,34 @@ func TestBaseAppLoggerWrites(t *testing.T) {
})
t.Run("test batch logs writes", func(t *testing.T) {
app.Settings().Logs.MaxDays = 1
synctest.Test(t, func(t *testing.T) {
app.Settings().Logs.MaxDays = 1
for i := 0; i < logsThreshold-1; i++ {
for i := 0; i < logsThreshold-1; i++ {
app.Logger().Error("test")
}
if total := totalLogs(app, t); total != 0 {
t.Fatalf("Expected no logs, got %d", total)
}
// should trigger batch write
app.Logger().Error("test")
}
if total := totalLogs(app, t); total != 0 {
t.Fatalf("Expected no logs, got %d", total)
}
// should be added for the next batch write
app.Logger().Error("test")
// should trigger batch write
app.Logger().Error("test")
if total := totalLogs(app, t); total != logsThreshold {
t.Fatalf("Expected %d logs, got %d", logsThreshold, total)
}
// should be added for the next batch write
app.Logger().Error("test")
// wait for 3 secs to check the timer trigger
synctest.Sleep(3000 * time.Millisecond)
if total := totalLogs(app, t); total != logsThreshold {
t.Fatalf("Expected %d logs, got %d", logsThreshold, total)
}
// wait for ~3 secs to check the timer trigger
time.Sleep(3200 * time.Millisecond)
if total := totalLogs(app, t); total != logsThreshold+1 {
t.Fatalf("Expected %d logs, got %d", logsThreshold+1, total)
}
if total := totalLogs(app, t); total != logsThreshold {
t.Fatalf("Expected %d logs, got %d", logsThreshold, total)
}
})
})
}
@@ -552,3 +556,19 @@ func TestBaseAppAuxDBDualBuilder(t *testing.T) {
}
}
}
func TestBaseAppTriggerOnTerminate(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
event := new(core.TerminateEvent)
event.App = app
// trigger OnTerminate multiple times to ensure that it doesn't deadlock
// https://github.com/pocketbase/pocketbase/pull/7305
app.OnTerminate().Trigger(event)
app.OnTerminate().Trigger(event)
app.OnTerminate().Trigger(event)
}
+8 -3
View File
@@ -4,12 +4,13 @@ import (
"cmp"
"context"
"database/sql"
"encoding/json"
"encoding/json/jsontext"
"encoding/json/v2"
"errors"
"fmt"
"slices"
validation "github.com/go-ozzo/ozzo-validation/v4"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/spf13/cast"
)
@@ -186,7 +187,11 @@ func (app *BaseApp) ImportCollections(toImport []map[string]any, deleteMissing b
)
if err := validator.run(); err != nil {
// serialize the validation error(s)
serializedErr, _ := json.MarshalIndent(err, "", " ")
serializedErr, _ := json.Marshal(
err,
jsontext.WithIndentPrefix(""),
jsontext.WithIndent(" "),
)
return validation.Errors{"collections": validation.NewError(
"validation_collections_import_failure",
+2 -2
View File
@@ -1,7 +1,7 @@
package core_test
import (
"encoding/json"
"encoding/json/v2"
"strings"
"testing"
@@ -449,7 +449,7 @@ func TestImportCollectionsCreateRules(t *testing.T) {
t.Fatal(err)
}
raw, err := json.Marshal(collection)
raw, err := json.Marshal(collection, json.Deterministic(true))
if err != nil {
t.Fatal(err)
}
+53 -19
View File
@@ -1,7 +1,7 @@
package core
import (
"encoding/json"
"encoding/json/v2"
"fmt"
"strconv"
"strings"
@@ -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
@@ -521,8 +522,6 @@ func (m *Collection) unmarshalRawOptions() error {
// For new/"blank" Collection models it replaces the model with a factory
// instance and then unmarshal the provided data one on top of it.
func (m *Collection) UnmarshalJSON(b []byte) error {
type alias *Collection
// initialize the default fields
// (e.g. in case the collection was NOT created using the designated factories)
if m.IsNew() && m.Type == "" {
@@ -539,50 +538,60 @@ func (m *Collection) UnmarshalJSON(b []byte) error {
*m = *blank
}
return json.Unmarshal(b, alias(m))
type alias Collection
return json.Unmarshal(b, (*alias)(m))
}
// MarshalJSON implements the [json.Marshaler] interface.
//
// Note that non-type related fields are ignored from the serialization
// (ex. for "view" colections the "auth" fields are skipped).
// (ex. for "view" collections the "auth" fields are skipped).
func (m Collection) MarshalJSON() ([]byte, error) {
switch m.Type {
case CollectionTypeView:
return json.Marshal(struct {
alias := struct {
baseCollection
collectionViewOptions
}{m.baseCollection, m.collectionViewOptions})
}{m.baseCollection, m.collectionViewOptions}
return json.Marshal(alias, json.Deterministic(true))
case CollectionTypeAuth:
alias := struct {
baseCollection
collectionAuthOptions
}{m.baseCollection, m.collectionAuthOptions}
// ensure that it is always returned as array
if alias.OAuth2.Providers == nil {
alias.OAuth2.Providers = []OAuth2ProviderConfig{}
}
// @todo to avoid the below changes consider omitting the field values from the individual structs json tags
//
// hide secret keys from the serialization
alias.AuthToken.Secret = ""
alias.FileToken.Secret = ""
alias.PasswordResetToken.Secret = ""
alias.EmailChangeToken.Secret = ""
alias.VerificationToken.Secret = ""
for i := range alias.OAuth2.Providers {
alias.OAuth2.Providers[i].ClientSecret = ""
if alias.OAuth2.Providers == nil {
// ensure that it is always returned as array
alias.OAuth2.Providers = []OAuth2ProviderConfig{}
} else {
// create a deep copy of the slice to avoid modifying the cached model state
redactedProviders := make([]OAuth2ProviderConfig, len(alias.OAuth2.Providers))
copy(redactedProviders, alias.OAuth2.Providers)
for i := range redactedProviders {
redactedProviders[i].ClientSecret = ""
}
alias.OAuth2.Providers = redactedProviders
}
return json.Marshal(alias)
return json.Marshal(alias, json.Deterministic(true))
default:
return json.Marshal(m.baseCollection)
return json.Marshal(m.baseCollection, json.Deterministic(true))
}
}
// String returns a string representation of the current collection.
func (m Collection) String() string {
raw, _ := json.Marshal(m)
raw, _ := m.MarshalJSON()
return string(raw)
}
@@ -813,6 +822,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()
}
@@ -898,8 +926,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
}
+73 -5
View File
@@ -1,12 +1,15 @@
package core
import (
"encoding/json/v2"
"errors"
"slices"
"strconv"
"strings"
"time"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/pocketbase/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/tools/auth"
"github.com/pocketbase/pocketbase/tools/list"
"github.com/pocketbase/pocketbase/tools/security"
@@ -60,7 +63,7 @@ func (m *Collection) setDefaultAuthOptions() {
},
MFA: MFAConfig{
Enabled: false,
Duration: 1800, // 30min
Duration: 600, // 10min
},
OTP: OTPConfig{
Enabled: false,
@@ -70,7 +73,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 +85,7 @@ func (m *Collection) setDefaultAuthOptions() {
},
VerificationToken: TokenConfig{
Secret: security.RandomString(50),
Duration: 259200, // 3days
Duration: 86400, // 1day
},
FileToken: TokenConfig{
Secret: security.RandomString(50),
@@ -409,6 +412,71 @@ type OAuth2Config struct {
Enabled bool `form:"enabled" json:"enabled"`
}
// UnmarshalJSON implements the [json.Unmarshaler] interface.
//
// The main difference from the standard unmarshalization is that
// instead of replacing the entire providers config slice, we ensure
// that partially submitted provider data (e.g. without clientSecret)
// is merged on per config level based on the provider name
// (https://github.com/pocketbase/pocketbase/issues/7815).
func (c *OAuth2Config) UnmarshalJSON(b []byte) error {
originalProviders := slices.Clone(c.Providers)
type alias OAuth2Config
err := json.Unmarshal(b, (*alias)(c))
if err != nil {
return err
}
if len(c.Providers) == 0 {
return nil
}
// unmarshal again but this time into a plain array of objects
// so that we have only the submitted fields and no zero defaults
plain := struct {
Providers []map[string]any `json:"providers"`
}{}
err = json.Unmarshal(b, &plain)
if err != nil {
return err
}
// no providers were submitted
if len(plain.Providers) == 0 {
return nil
}
if len(c.Providers) != len(plain.Providers) {
return errors.New("the length of the plain unmarshalized providers and the ones from the config doesn't match")
}
ProvidersMergeLoop:
for i, plain := range plain.Providers {
for _, original := range originalProviders {
if original.Name == plain["name"] {
raw, err := json.Marshal(plain)
if err != nil {
return err
}
// unmarshal the new plain data on top of the original one
err = json.Unmarshal(raw, &original)
if err != nil {
return err
}
// reassigne to the updated original
c.Providers[i] = original
continue ProvidersMergeLoop
}
}
}
return nil
}
// GetProviderConfig returns the first OAuth2ProviderConfig that matches the specified name.
//
// Returns false and zero config if no such provider is available in c.Providers.
+73 -3
View File
@@ -2,7 +2,7 @@ package core_test
import (
"bytes"
"encoding/json"
"encoding/json/v2"
"fmt"
"strings"
"testing"
@@ -712,6 +712,76 @@ func TestPasswordAuthConfigValidate(t *testing.T) {
}
}
func TestOAuth2ConfigUnmarshalJSON(t *testing.T) {
t.Parallel()
scenarios := []struct {
name string
newJSON string
expected string
}{
{
"missing",
`{
"enabled": true,
"mappedFields": {"username": "username_test"}
}`,
`{"providers":[{"pkce":null,"name":"a","clientId":"a_clientId","clientSecret":"a_clientSecret","authURL":"","tokenURL":"","userInfoURL":"","displayName":"","extra":{}},{"pkce":null,"name":"b","clientId":"b_clientId","clientSecret":"b_clientSecret","authURL":"","tokenURL":"","userInfoURL":"","displayName":"","extra":{}}],"mappedFields":{"id":"","name":"name_test","username":"username_test","avatarURL":""},"enabled":true}`,
},
{
"empty",
`{
"enabled": true,
"mappedFields": {"username": "username_test"},
"providers": []
}`,
`{"providers":[],"mappedFields":{"id":"","name":"name_test","username":"username_test","avatarURL":""},"enabled":true}`,
},
{
"non-empty",
`{
"enabled": true,
"mappedFields": {"username": "username_test"},
"providers": [
{"name": "c", "clientId": "c_clientId", "clientSecret": "c_clientSecret"},
{"name": "a", "displayName": "a_displayName"}
]
}`,
`{"providers":[{"pkce":null,"name":"c","clientId":"c_clientId","clientSecret":"c_clientSecret","authURL":"","tokenURL":"","userInfoURL":"","displayName":"","extra":{}},{"pkce":null,"name":"a","clientId":"a_clientId","clientSecret":"a_clientSecret","authURL":"","tokenURL":"","userInfoURL":"","displayName":"a_displayName","extra":{}}],"mappedFields":{"id":"","name":"name_test","username":"username_test","avatarURL":""},"enabled":true}`,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
config := core.OAuth2Config{
Enabled: false,
MappedFields: core.OAuth2KnownFields{
Name: "name_test",
},
Providers: []core.OAuth2ProviderConfig{
{Name: "a", ClientId: "a_clientId", ClientSecret: "a_clientSecret"},
{Name: "b", ClientId: "b_clientId", ClientSecret: "b_clientSecret"},
},
}
err := json.Unmarshal([]byte(s.newJSON), &config)
if err != nil {
t.Fatal(err)
}
raw, err := json.Marshal(config, json.Deterministic(true))
if err != nil {
t.Fatal(err)
}
rawStr := string(raw)
if rawStr != s.expected {
t.Fatalf("Expected OAuth2ProviderConfig\n%s\ngot\n%s", s.expected, rawStr)
}
})
}
}
func TestOAuth2ConfigGetProviderConfig(t *testing.T) {
scenarios := []struct {
name string
@@ -1016,8 +1086,8 @@ func TestOAuth2ProviderConfigInitProvider(t *testing.T) {
t.Fatalf("Expected PKCE %v, got %v", *s.expectedConfig.PKCE, provider.PKCE())
}
rawMeta, _ := json.Marshal(provider.Extra())
expectedMeta, _ := json.Marshal(s.expectedConfig.Extra)
rawMeta, _ := json.Marshal(provider.Extra(), json.Deterministic(true))
expectedMeta, _ := json.Marshal(s.expectedConfig.Extra, json.Deterministic(true))
if !bytes.Equal(rawMeta, expectedMeta) {
t.Fatalf("Expected PKCE %v, got %v", *s.expectedConfig.PKCE, provider.PKCE())
}
+12 -9
View File
@@ -2,11 +2,12 @@ package core
// Common settings placeholder tokens
const (
EmailPlaceholderAppName string = "{APP_NAME}"
EmailPlaceholderAppURL string = "{APP_URL}"
EmailPlaceholderToken string = "{TOKEN}"
EmailPlaceholderOTP string = "{OTP}"
EmailPlaceholderOTPId string = "{OTP_ID}"
EmailPlaceholderAppName string = "{APP_NAME}"
EmailPlaceholderAppURL string = "{APP_URL}"
EmailPlaceholderToken string = "{TOKEN}"
EmailPlaceholderOTP string = "{OTP}"
EmailPlaceholderOTPId string = "{OTP_ID}"
EmailPlaceholderAlertInfo string = "{ALERT_INFO}"
)
var defaultVerificationTemplate = EmailTemplate{
@@ -17,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
@@ -30,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
@@ -44,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
@@ -65,9 +67,10 @@ var defaultOTPTemplate = EmailTemplate{
var defaultAuthAlertTemplate = EmailTemplate{
Subject: "Login from a new location",
Body: `<p>Hello,</p>
<p>We noticed a login to your ` + EmailPlaceholderAppName + ` account from a new location.</p>
<p>If this was you, you may disregard this email.</p>
<p>We noticed a login to your ` + EmailPlaceholderAppName + ` account from a new location:</p>
<p><em>` + EmailPlaceholderAlertInfo + `</em></p>
<p><strong>If this wasn't you, you should immediately change your ` + EmailPlaceholderAppName + ` account password to revoke access from all other locations.</strong></p>
<p>If this was you, you may disregard this email.</p>
<p>
Thanks,<br/>
` + EmailPlaceholderAppName + ` team
+108 -29
View File
@@ -2,7 +2,7 @@ package core_test
import (
"context"
"encoding/json"
"encoding/json/v2"
"errors"
"fmt"
"slices"
@@ -618,7 +618,7 @@ func TestCollectionUnmarshalJSON(t *testing.T) {
t.Fatal(err)
}
rawResult, err := json.Marshal(collection)
rawResult, err := json.Marshal(collection, json.Deterministic(true))
if err != nil {
t.Fatal(err)
}
@@ -760,6 +760,46 @@ func TestCollectionSerialize(t *testing.T) {
}
}
func TestCollectionSerializeNotModifyingCache(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
c, err := app.FindCachedCollectionByNameOrId("users")
if err != nil {
t.Fatal(err)
}
_, err = json.Marshal(c)
if err != nil {
t.Fatal(err)
}
redactedFields := map[string]string{
"AuthToken.Secret": c.AuthToken.Secret,
"FileToken.Secret": c.FileToken.Secret,
"PasswordResetToken.Secret": c.PasswordResetToken.Secret,
"EmailChangeToken.Secret": c.EmailChangeToken.Secret,
"VerificationToken.Secret": c.VerificationToken.Secret,
}
if len(c.OAuth2.Providers) == 0 {
t.Fatal("Expected at least one users OAuth2 provider, got 0")
}
for _, p := range c.OAuth2.Providers {
redactedFields[p.Name+".ClientSecret"] = p.ClientSecret
}
for k, v := range redactedFields {
t.Run(k, func(t *testing.T) {
if v == "" {
t.Fatalf("Expected the redacted field %q to remain unmodified after serialization, got empty value", k)
}
})
}
}
func TestCollectionDBExport(t *testing.T) {
t.Parallel()
@@ -777,19 +817,19 @@ func TestCollectionDBExport(t *testing.T) {
}{
{
"unknown",
`{"createRule":"1=3","created":"2024-07-01 01:02:03.456Z","deleteRule":"1=5","fields":[{"hidden":false,"id":"f1_id","name":"f1","presentable":false,"required":false,"system":true,"type":"bool"},{"hidden":false,"id":"f2_id","name":"f2","presentable":false,"required":true,"system":false,"type":"bool"}],"id":"test_id","indexes":["CREATE INDEX idx1 on test_name(id)","CREATE INDEX idx2 on test_name(id)"],"listRule":"1=1","name":"test_name","options":"{}","system":true,"type":"unknown","updateRule":"1=4","updated":"2024-07-01 01:02:03.456Z","viewRule":"1=7"}`,
`{"createRule":"1=3","created":"2024-07-01 01:02:03.456Z","deleteRule":"1=5","fields":[{"help":"","hidden":false,"id":"f1_id","name":"f1","presentable":false,"required":false,"system":true,"type":"bool"},{"help":"","hidden":false,"id":"f2_id","name":"f2","presentable":false,"required":true,"system":false,"type":"bool"}],"id":"test_id","indexes":["CREATE INDEX idx1 on test_name(id)","CREATE INDEX idx2 on test_name(id)"],"listRule":"1=1","name":"test_name","options":"{}","system":true,"type":"unknown","updateRule":"1=4","updated":"2024-07-01 01:02:03.456Z","viewRule":"1=7"}`,
},
{
core.CollectionTypeBase,
`{"createRule":"1=3","created":"2024-07-01 01:02:03.456Z","deleteRule":"1=5","fields":[{"hidden":false,"id":"f1_id","name":"f1","presentable":false,"required":false,"system":true,"type":"bool"},{"hidden":false,"id":"f2_id","name":"f2","presentable":false,"required":true,"system":false,"type":"bool"}],"id":"test_id","indexes":["CREATE INDEX idx1 on test_name(id)","CREATE INDEX idx2 on test_name(id)"],"listRule":"1=1","name":"test_name","options":"{}","system":true,"type":"base","updateRule":"1=4","updated":"2024-07-01 01:02:03.456Z","viewRule":"1=7"}`,
`{"createRule":"1=3","created":"2024-07-01 01:02:03.456Z","deleteRule":"1=5","fields":[{"help":"","hidden":false,"id":"f1_id","name":"f1","presentable":false,"required":false,"system":true,"type":"bool"},{"help":"","hidden":false,"id":"f2_id","name":"f2","presentable":false,"required":true,"system":false,"type":"bool"}],"id":"test_id","indexes":["CREATE INDEX idx1 on test_name(id)","CREATE INDEX idx2 on test_name(id)"],"listRule":"1=1","name":"test_name","options":"{}","system":true,"type":"base","updateRule":"1=4","updated":"2024-07-01 01:02:03.456Z","viewRule":"1=7"}`,
},
{
core.CollectionTypeView,
`{"createRule":"1=3","created":"2024-07-01 01:02:03.456Z","deleteRule":"1=5","fields":[{"hidden":false,"id":"f1_id","name":"f1","presentable":false,"required":false,"system":true,"type":"bool"},{"hidden":false,"id":"f2_id","name":"f2","presentable":false,"required":true,"system":false,"type":"bool"}],"id":"test_id","indexes":["CREATE INDEX idx1 on test_name(id)","CREATE INDEX idx2 on test_name(id)"],"listRule":"1=1","name":"test_name","options":{"viewQuery":"select 1"},"system":true,"type":"view","updateRule":"1=4","updated":"2024-07-01 01:02:03.456Z","viewRule":"1=7"}`,
`{"createRule":"1=3","created":"2024-07-01 01:02:03.456Z","deleteRule":"1=5","fields":[{"help":"","hidden":false,"id":"f1_id","name":"f1","presentable":false,"required":false,"system":true,"type":"bool"},{"help":"","hidden":false,"id":"f2_id","name":"f2","presentable":false,"required":true,"system":false,"type":"bool"}],"id":"test_id","indexes":["CREATE INDEX idx1 on test_name(id)","CREATE INDEX idx2 on test_name(id)"],"listRule":"1=1","name":"test_name","options":{"viewQuery":"select 1"},"system":true,"type":"view","updateRule":"1=4","updated":"2024-07-01 01:02:03.456Z","viewRule":"1=7"}`,
},
{
core.CollectionTypeAuth,
`{"createRule":"1=3","created":"2024-07-01 01:02:03.456Z","deleteRule":"1=5","fields":[{"hidden":false,"id":"f1_id","name":"f1","presentable":false,"required":false,"system":true,"type":"bool"},{"hidden":false,"id":"f2_id","name":"f2","presentable":false,"required":true,"system":false,"type":"bool"}],"id":"test_id","indexes":["CREATE INDEX idx1 on test_name(id)","CREATE INDEX idx2 on test_name(id)"],"listRule":"1=1","name":"test_name","options":{"authRule":null,"manageRule":"1=6","authAlert":{"enabled":false,"emailTemplate":{"subject":"","body":""}},"oauth2":{"providers":null,"mappedFields":{"id":"","name":"","username":"","avatarURL":""},"enabled":false},"passwordAuth":{"enabled":false,"identityFields":null},"mfa":{"enabled":false,"duration":0,"rule":""},"otp":{"enabled":false,"duration":0,"length":0,"emailTemplate":{"subject":"","body":""}},"authToken":{"duration":0},"passwordResetToken":{"duration":0},"emailChangeToken":{"duration":0},"verificationToken":{"duration":0},"fileToken":{"duration":0},"verificationTemplate":{"subject":"","body":""},"resetPasswordTemplate":{"subject":"","body":""},"confirmEmailChangeTemplate":{"subject":"","body":""}},"system":true,"type":"auth","updateRule":"1=4","updated":"2024-07-01 01:02:03.456Z","viewRule":"1=7"}`,
`{"createRule":"1=3","created":"2024-07-01 01:02:03.456Z","deleteRule":"1=5","fields":[{"help":"","hidden":false,"id":"f1_id","name":"f1","presentable":false,"required":false,"system":true,"type":"bool"},{"help":"","hidden":false,"id":"f2_id","name":"f2","presentable":false,"required":true,"system":false,"type":"bool"}],"id":"test_id","indexes":["CREATE INDEX idx1 on test_name(id)","CREATE INDEX idx2 on test_name(id)"],"listRule":"1=1","name":"test_name","options":{"authRule":null,"manageRule":"1=6","authAlert":{"enabled":false,"emailTemplate":{"subject":"","body":""}},"oauth2":{"providers":[],"mappedFields":{"id":"","name":"","username":"","avatarURL":""},"enabled":false},"passwordAuth":{"enabled":false,"identityFields":[]},"mfa":{"enabled":false,"duration":0,"rule":""},"otp":{"enabled":false,"duration":0,"length":0,"emailTemplate":{"subject":"","body":""}},"authToken":{"duration":0},"passwordResetToken":{"duration":0},"emailChangeToken":{"duration":0},"verificationToken":{"duration":0},"fileToken":{"duration":0},"verificationTemplate":{"subject":"","body":""},"resetPasswordTemplate":{"subject":"","body":""},"confirmEmailChangeTemplate":{"subject":"","body":""}},"system":true,"type":"auth","updateRule":"1=4","updated":"2024-07-01 01:02:03.456Z","viewRule":"1=7"}`,
},
}
@@ -820,7 +860,7 @@ func TestCollectionDBExport(t *testing.T) {
t.Fatal(err)
}
raw, err := json.Marshal(result)
raw, err := json.Marshal(result, json.Deterministic(true))
if err != nil {
t.Fatal(err)
}
@@ -1536,60 +1576,62 @@ func TestCollectionSaveViewWrapping(t *testing.T) {
viewName := "test_wrapping"
// note: some of the queries use "limit 0" because the tested field value could be empty
// which will trigger the extra sample records validation that are not important for this test
scenarios := []struct {
name string
query string
expected string
}{
{
"no wrapping - text field",
"select text as id, bool from demo1",
"CREATE VIEW `test_wrapping` AS SELECT * FROM (select text as id, bool from demo1)",
"no wrapping - id field",
"select id, bool from demo1",
"CREATE VIEW `test_wrapping` AS SELECT * FROM (select id, bool from demo1)",
},
{
"no wrapping - id field",
"select text as id, bool from demo1",
"CREATE VIEW `test_wrapping` AS SELECT * FROM (select text as id, bool from demo1)",
"no wrapping - text field",
"select text as id, bool from demo1 limit 0",
"CREATE VIEW `test_wrapping` AS SELECT * FROM (select text as id, bool from demo1 limit 0)",
},
{
"no wrapping - relation field",
"select rel_one as id, bool from demo1",
"CREATE VIEW `test_wrapping` AS SELECT * FROM (select rel_one as id, bool from demo1)",
"select rel_one as id, bool from demo1 limit 0",
"CREATE VIEW `test_wrapping` AS SELECT * FROM (select rel_one as id, bool from demo1 limit 0)",
},
{
"no wrapping - select field",
"select select_many as id, bool from demo1",
"CREATE VIEW `test_wrapping` AS SELECT * FROM (select select_many as id, bool from demo1)",
"select select_many as id, bool from demo1 limit 0",
"CREATE VIEW `test_wrapping` AS SELECT * FROM (select select_many as id, bool from demo1 limit 0)",
},
{
"no wrapping - email field",
"select email as id, bool from demo1",
"CREATE VIEW `test_wrapping` AS SELECT * FROM (select email as id, bool from demo1)",
"select email as id, bool from demo1 limit 0",
"CREATE VIEW `test_wrapping` AS SELECT * FROM (select email as id, bool from demo1 limit 0)",
},
{
"no wrapping - datetime field",
"select datetime as id, bool from demo1",
"CREATE VIEW `test_wrapping` AS SELECT * FROM (select datetime as id, bool from demo1)",
"select datetime as id, bool from demo1 limit 0",
"CREATE VIEW `test_wrapping` AS SELECT * FROM (select datetime as id, bool from demo1 limit 0)",
},
{
"no wrapping - url field",
"select url as id, bool from demo1",
"CREATE VIEW `test_wrapping` AS SELECT * FROM (select url as id, bool from demo1)",
"select url as id, bool from demo1 limit 0",
"CREATE VIEW `test_wrapping` AS SELECT * FROM (select url as id, bool from demo1 limit 0)",
},
{
"wrapping - bool field",
"select bool as id, text as txt, url from demo1",
"CREATE VIEW `test_wrapping` AS SELECT * FROM (SELECT CAST(`id` as TEXT) `id`,`txt`,`url` FROM (select bool as id, text as txt, url from demo1))",
"select bool as id, text as txt, url from demo1 limit 0",
"CREATE VIEW `test_wrapping` AS SELECT * FROM (SELECT CAST(`id` as TEXT) `id`,`txt`,`url` FROM (select bool as id, text as txt, url from demo1 limit 0))",
},
{
"wrapping - bool field (different order)",
"select text as txt, url, bool as id from demo1",
"CREATE VIEW `test_wrapping` AS SELECT * FROM (SELECT `txt`,`url`,CAST(`id` as TEXT) `id` FROM (select text as txt, url, bool as id from demo1))",
"select text as txt, url, bool as id from demo1 limit 0",
"CREATE VIEW `test_wrapping` AS SELECT * FROM (SELECT `txt`,`url`,CAST(`id` as TEXT) `id` FROM (select text as txt, url, bool as id from demo1 limit 0))",
},
{
"wrapping - json field",
"select json as id, text, url from demo1",
"CREATE VIEW `test_wrapping` AS SELECT * FROM (SELECT CAST(`id` as TEXT) `id`,`text`,`url` FROM (select json as id, text, url from demo1))",
"select json as id, text, url from demo1 limit 0",
"CREATE VIEW `test_wrapping` AS SELECT * FROM (SELECT CAST(`id` as TEXT) `id`,`text`,`url` FROM (select json as id, text, url from demo1 limit 0))",
},
{
"wrapping - numeric id",
@@ -1636,3 +1678,40 @@ func TestCollectionSaveViewWrapping(t *testing.T) {
})
}
}
func TestCollectionSaveIndexesTableNameNormalization(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
dummyCollection := core.NewBaseCollection("new_test")
dummyCollection.Fields.Add(&core.TextField{Name: "test"})
dummyCollection.Indexes = []string{
"create index `new_test_idx1` on `` (`test`) where 1=1",
"create index `new_test_idx2` on `test` (`test`) where 1=2",
"create index `new_test_idx3` on `someting_else` (`test`) where 1=3",
}
err := app.Save(dummyCollection)
if err != nil {
t.Fatal(err)
}
// refetch a clean state
dummyCollection, err = app.FindCollectionByNameOrId(dummyCollection.Name)
if err != nil {
t.Fatal(err)
}
if len(dummyCollection.Indexes) != 3 {
t.Fatalf("Expected 3 indexes, got %v", dummyCollection.Indexes)
}
for _, raw := range dummyCollection.Indexes {
parsed := dbutils.ParseIndex(raw)
if parsed.TableName != dummyCollection.Name {
t.Fatalf("Expected all indexes to have tableName %q, found %q:\n%s", dummyCollection.Name, parsed.TableName, raw)
}
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
package core
import (
validation "github.com/go-ozzo/ozzo-validation/v4"
validation "github.com/pocketbase/ozzo-validation/v4"
)
var _ optionsValidator = (*collectionViewOptions)(nil)
@@ -41,6 +41,24 @@ func TestCollectionViewOptionsValidate(t *testing.T) {
},
expectedErrors: []string{"fields", "viewQuery"},
},
{
name: "view with valid query but empty sample id",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewViewCollection("new_auth")
c.ViewQuery = "select '' as id"
return c, nil
},
expectedErrors: []string{"viewQuery"},
},
{
name: "view with valid query but duplicated sample id",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewViewCollection("new_auth")
c.ViewQuery = "(select 'a' as id union all select 'a' as id union all select 'c' as id)"
return c, nil
},
expectedErrors: []string{"viewQuery"},
},
{
name: "view with valid query",
collection: func(app core.App) (*core.Collection, error) {
+45 -82
View File
@@ -3,7 +3,7 @@ package core
import (
"bytes"
"database/sql"
"encoding/json"
"encoding/json/v2"
"errors"
"fmt"
"slices"
@@ -250,52 +250,6 @@ func (app *BaseApp) TruncateCollection(collection *Collection) error {
// -------------------------------------------------------------------
// saveViewCollection persists the provided View collection changes:
// - deletes the old related SQL view (if any)
// - creates a new SQL view with the latest newCollection.Options.Query
// - generates new feilds list based on newCollection.Options.Query
// - updates newCollection.Fields based on the generated view table info and query
// - saves the newCollection
//
// This method returns an error if newCollection is not a "view".
func saveViewCollection(app App, newCollection, oldCollection *Collection) error {
if !newCollection.IsView() {
return errors.New("not a view collection")
}
return app.RunInTransaction(func(txApp App) error {
query := newCollection.ViewQuery
// generate collection fields from the query
viewFields, err := txApp.CreateViewFields(query)
if err != nil {
return err
}
// delete old renamed view
if oldCollection != nil {
if err := txApp.DeleteView(oldCollection.Name); err != nil {
return err
}
}
// wrap view query if necessary
query, err = normalizeViewQueryId(txApp, query)
if err != nil {
return fmt.Errorf("failed to normalize view query id: %w", err)
}
// (re)create the view
if err := txApp.SaveView(newCollection.Name, query); err != nil {
return err
}
newCollection.Fields = viewFields
return txApp.Save(newCollection)
})
}
// normalizeViewQueryId wraps (if necessary) the provided view query
// with a subselect to ensure that the id column is a text since
// currently we don't support non-string model ids
@@ -342,50 +296,59 @@ func resaveViewsWithChangedFields(app App, excludeIds ...string) error {
}
return app.RunInTransaction(func(txApp App) error {
var collectionErrors []error
for _, collection := range collections {
if len(excludeIds) > 0 && list.ExistInSlice(collection.Id, excludeIds) {
continue
}
// clone the existing fields for temp modifications
oldFields, err := collection.Fields.Clone()
if err != nil {
return err
check := func() error {
// clone the existing fields for temp modifications
oldFields, err := collection.Fields.Clone()
if err != nil {
return err
}
// generate new fields from the query
newFields, err := txApp.CreateViewFields(collection.ViewQuery)
if err != nil {
return err
}
// unset the fields' ids to exclude from the comparison
for _, f := range oldFields {
f.SetId("")
}
for _, f := range newFields {
f.SetId("")
}
encodedNewFields, err := json.Marshal(newFields, json.Deterministic(true))
if err != nil {
return err
}
encodedOldFields, err := json.Marshal(oldFields, json.Deterministic(true))
if err != nil {
return err
}
if bytes.EqualFold(encodedNewFields, encodedOldFields) {
return nil // no changes
}
return txApp.Save(collection)
}
// generate new fields from the query
newFields, err := txApp.CreateViewFields(collection.ViewQuery)
if err != nil {
return err
}
// unset the fields' ids to exclude from the comparison
for _, f := range oldFields {
f.SetId("")
}
for _, f := range newFields {
f.SetId("")
}
encodedNewFields, err := json.Marshal(newFields)
if err != nil {
return err
}
encodedOldFields, err := json.Marshal(oldFields)
if err != nil {
return err
}
if bytes.EqualFold(encodedNewFields, encodedOldFields) {
continue // no changes
}
if err := saveViewCollection(txApp, collection, nil); err != nil {
return err
if err := check(); err != nil {
collectionErrors = append(
collectionErrors,
fmt.Errorf("[%s] %w", collection.Name, err),
)
}
}
return nil
return errors.Join(collectionErrors...)
})
}
+5 -3
View File
@@ -6,8 +6,8 @@ import (
"strconv"
"strings"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/dbx"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/tools/dbutils"
"github.com/pocketbase/pocketbase/tools/security"
)
@@ -306,8 +306,10 @@ func dropCollectionIndexes(app App, collection *Collection) error {
for _, raw := range collection.Indexes {
parsed := dbutils.ParseIndex(raw)
if !parsed.IsValid() {
continue
// note: don't check IsValid because the index table name may not be populated
// (https://github.com/pocketbase/pocketbase/issues/7689)
if parsed.IndexName == "" {
return fmt.Errorf("failed to dop index - missing index name: %s", raw)
}
_, err := txApp.DB().NewQuery(fmt.Sprintf("DROP INDEX IF EXISTS [[%s]]", parsed.IndexName)).Execute()
+49 -3
View File
@@ -2,7 +2,7 @@ package core_test
import (
"bytes"
"encoding/json"
"encoding/json/v2"
"testing"
"github.com/pocketbase/dbx"
@@ -278,12 +278,12 @@ func TestSingleVsMultipleValuesNormalization(t *testing.T) {
t.Fatalf("Failed to load record: %v", err)
}
encodedResult, err := json.Marshal(result)
encodedResult, err := json.Marshal(result, json.Deterministic(true))
if err != nil {
t.Fatalf("Failed to encode result: %v", err)
}
encodedExpectation, err := json.Marshal(s.expected)
encodedExpectation, err := json.Marshal(s.expected, json.Deterministic(true))
if err != nil {
t.Fatalf("Failed to encode expectation: %v", err)
}
@@ -294,3 +294,49 @@ func TestSingleVsMultipleValuesNormalization(t *testing.T) {
})
}
}
func TestDropIndexWithoutTableName(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
properIndex := "CREATE INDEX `new_test_idx2` ON `new_test` (`test`)"
indexWithoutTableName := "CREATE INDEX `new_test_idx2` ON `` (`test`)"
dummyCollection := core.NewBaseCollection("new_test")
dummyCollection.Fields.Add(&core.TextField{Name: "test"})
dummyCollection.Indexes = []string{properIndex}
err := app.Save(dummyCollection)
if err != nil {
t.Fatal(err)
}
// resave without table name but without hooks to avoid the normalizations
dummyCollection.Indexes[0] = indexWithoutTableName
err = app.UnsafeWithoutHooks().Save(dummyCollection)
if err != nil {
t.Fatal(err)
}
dummyCollection, err = app.FindCollectionByNameOrId(dummyCollection.Name)
if err != nil {
t.Fatal(err)
}
// resave should normalize the index
err = app.Save(dummyCollection)
if err != nil {
t.Fatal(err)
}
dummyCollection, err = app.FindCollectionByNameOrId(dummyCollection.Name)
if err != nil {
t.Fatal(err)
}
if len(dummyCollection.Indexes) != 1 || dummyCollection.Indexes[0] != properIndex {
t.Fatalf("Expected exactly 1 index\n%s\ngot\n%v", properIndex, dummyCollection.Indexes)
}
}
+11 -7
View File
@@ -7,8 +7,8 @@ import (
"strconv"
"strings"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/dbx"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core/validators"
"github.com/pocketbase/pocketbase/tools/dbutils"
"github.com/pocketbase/pocketbase/tools/list"
@@ -314,11 +314,15 @@ func (cv *collectionValidator) checkViewQuery(value any) error {
return nil // nothing to check
}
if _, err := cv.app.CreateViewFields(v); err != nil {
return validation.NewError(
"validation_invalid_view_query",
fmt.Sprintf("Invalid query - %s", err.Error()),
)
_, err := cv.app.DryRunView(v, 10)
if err != nil {
rawErr := err.Error()
if len(rawErr) > 500 {
// restrict just as an extra precaution
rawErr = rawErr[:500]
}
return validation.NewError("validation_invalid_view_query", "Invalid query - "+rawErr)
}
return nil
@@ -489,7 +493,7 @@ func (validator *collectionValidator) checkRule(value any) error {
return nil // nothing to check
}
r := NewRecordFieldResolver(validator.app, validator.new, nil, true)
r := NewRecordFieldResolver(validator.app, validator.new, &RequestInfo{}, true)
_, err := search.FilterData(vStr).BuildExpr(r)
if err != nil {
return validation.NewError("validation_invalid_rule", "Invalid rule. Raw error: "+err.Error())
+3 -3
View File
@@ -319,8 +319,8 @@ func TestCollectionValidate(t *testing.T) {
c.ListRule = types.Pointer("!invalid")
c.ViewRule = types.Pointer("missing = 123")
c.CreateRule = types.Pointer("id = 123 && missing = 456")
c.UpdateRule = types.Pointer("(id = 123")
c.DeleteRule = types.Pointer("missing = 123")
c.UpdateRule = types.Pointer("@request.body.missing:changed = false")
c.DeleteRule = types.Pointer("(id=123")
return c, nil
},
expectedErrors: []string{"listRule", "viewRule", "createRule", "updateRule", "deleteRule"},
@@ -333,7 +333,7 @@ func TestCollectionValidate(t *testing.T) {
c.ListRule = types.Pointer("")
c.ViewRule = types.Pointer("f1 = 123")
c.CreateRule = types.Pointer("id = 123 && f1 = 456")
c.UpdateRule = types.Pointer("(id = 123)")
c.UpdateRule = types.Pointer("(id = 123 && @request.body.f1:changed = false)")
c.DeleteRule = types.Pointer("f1 = 123")
return c, nil
},
+1 -1
View File
@@ -10,8 +10,8 @@ import (
"strconv"
"strings"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/dbx"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/tools/security"
"github.com/spf13/cast"
)
+1 -1
View File
@@ -11,7 +11,7 @@ func DefaultDBConnect(dbPath string) (*dbx.DB, error) {
// Note: the busy_timeout pragma must be first because
// the connection needs to be set to block on busy before WAL mode
// is set in case it hasn't been already set by another connection.
pragmas := "?_pragma=busy_timeout(10000)&_pragma=journal_mode(WAL)&_pragma=journal_size_limit(200000000)&_pragma=synchronous(NORMAL)&_pragma=foreign_keys(ON)&_pragma=temp_store(MEMORY)&_pragma=cache_size(-16000)"
pragmas := "?_pragma=busy_timeout(10000)&_pragma=journal_mode(WAL)&_pragma=journal_size_limit(200000000)&_pragma=synchronous(NORMAL)&_pragma=foreign_keys(ON)&_pragma=temp_store(MEMORY)&_pragma=cache_size(-32000)&_defensive=1"
db, err := dbx.Open("sqlite", dbPath+pragmas)
if err != nil {
+3 -3
View File
@@ -85,11 +85,11 @@ func (app *BaseApp) TableIndexes(tableName string) (map[string]string, error) {
// This method is a no-op if a table with the provided name doesn't exist.
//
// NB! Be aware that this method is vulnerable to SQL injection and the
// "tableName" argument must come only from trusted input!
func (app *BaseApp) DeleteTable(tableName string) error {
// "dangerousTableName" argument must come only from trusted input!
func (app *BaseApp) DeleteTable(dangerousTableName string) error {
_, err := app.NonconcurrentDB().NewQuery(fmt.Sprintf(
"DROP TABLE IF EXISTS {{%s}}",
tableName,
dangerousTableName,
)).Execute()
return err
+6 -2
View File
@@ -3,7 +3,7 @@ package core_test
import (
"context"
"database/sql"
"encoding/json"
"encoding/json/v2"
"fmt"
"slices"
"testing"
@@ -120,7 +120,11 @@ func TestTableInfo(t *testing.T) {
t.Run(fmt.Sprintf("%d_%s", i, s.tableName), func(t *testing.T) {
rows, _ := app.TableInfo(s.tableName)
raw, err := json.Marshal(rows)
raw, err := json.Marshal(
rows,
json.Deterministic(true),
json.FormatNilSliceAsNull(true),
)
if err != nil {
t.Fatal(err)
}
+1 -1
View File
@@ -3,7 +3,7 @@ package core
import (
"net/http"
validation "github.com/go-ozzo/ozzo-validation/v4"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/tools/hook"
)
+5 -5
View File
@@ -1,7 +1,7 @@
package core_test
import (
"encoding/json"
"encoding/json/v2"
"net/http"
"strings"
"testing"
@@ -183,7 +183,7 @@ func TestRequestEventRequestInfo(t *testing.T) {
t.Fatalf("Failed to resolve request info: %v", err)
}
raw, err := json.Marshal(info)
raw, err := json.Marshal(info, json.Deterministic(true))
if err != nil {
t.Fatalf("Failed to serialize request info: %v", err)
}
@@ -205,7 +205,7 @@ func TestRequestEventRequestInfo(t *testing.T) {
t.Fatalf("Failed to resolve request info: %v", err)
}
raw, err := json.Marshal(info)
raw, err := json.Marshal(info, json.Deterministic(true))
if err != nil {
t.Fatalf("Failed to serialize request info: %v", err)
}
@@ -308,7 +308,7 @@ func TestRequestInfoClone(t *testing.T) {
// check the original data
// ---
originalRaw, err := json.Marshal(info)
originalRaw, err := json.Marshal(info, json.Deterministic(true))
if err != nil {
t.Fatalf("Failed to serialize original request info: %v", err)
}
@@ -321,7 +321,7 @@ func TestRequestInfoClone(t *testing.T) {
// check the clone data
// ---
cloneRaw, err := json.Marshal(clone)
cloneRaw, err := json.Marshal(clone, json.Deterministic(true))
if err != nil {
t.Fatalf("Failed to serialize clone request info: %v", err)
}
+62 -1
View File
@@ -2,11 +2,13 @@ package core
import (
"context"
"io/fs"
"net"
"net/http"
"time"
"github.com/pocketbase/pocketbase/tools/auth"
"github.com/pocketbase/pocketbase/tools/filesystem"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/mailer"
"github.com/pocketbase/pocketbase/tools/router"
@@ -57,6 +59,9 @@ type baseCollectionEventData struct {
Collection *Collection
}
// @todo consider storing the original collection name and use that as a tag
// to avoid the ambiguity when the collection is being modified (#7613);
// for new collection also maybe return empty tags?
func (e *baseCollectionEventData) Tags() []string {
if e.Collection == nil {
return nil
@@ -125,6 +130,21 @@ type ServeEvent struct {
//
// Set it to nil if you want to skip the installer.
InstallerFunc func(app App, systemSuperuser *Record, baseURL string) error
// @todo experimental
//
// UIExtensions is a list with the superuser UI extensions.
UIExtensions []UIExtension
}
type UIExtension struct {
// Name is the name of the extension.
// It is also used as path segment for the registered public extension endpoint
// (e.g. /_/extensions/{name}/*)
Name string
// FS is the extension file system.
FS fs.FS
}
// -------------------------------------------------------------------
@@ -169,6 +189,24 @@ type MailerRecordEvent struct {
Meta map[string]any
}
// -------------------------------------------------------------------
// Filesystem events data
// -------------------------------------------------------------------
type FilesystemNewWriterEvent struct {
hook.Event
*filesystem.NewWriterEvent
App App
}
type FilesystemDeleteEvent struct {
hook.Event
*filesystem.DeleteEvent
App App
}
// -------------------------------------------------------------------
// Model events data
// -------------------------------------------------------------------
@@ -384,6 +422,13 @@ type FileDownloadRequestEvent struct {
FileField *FileField
ServedPath string
ServedName string
// ThumbError indicates the a thumb wasn't able to be generated
// (e.g. because it didn't satisfy the support image formats or it timed out).
//
// Note that PocketBase fallbacks to the original file in case of a thumb error,
// but developers can check the field and provide their own custom thumb generation if necessary.
ThumbError error
}
// -------------------------------------------------------------------
@@ -422,8 +467,24 @@ type RealtimeConnectRequestEvent struct {
Client subscriptions.Client
// note: modifying it after the connect has no effect
// IdleTimeout specifies the max duration to wait for a new message
// before closing the connection.
//
// Modifying the value after the connection has been established has no effect.
//
// Defaults to 5 minutes.
IdleTimeout time.Duration
// MaxTimeout specifies the maximum duration a realtime connection
// can remain open (including even if there are ongoing messages).
//
// Once the specified duration expires, the current connection will
// be terminated, until a client reconnect is issued (if the client is still active).
//
// Modifying the value after the connection has been established has no effect.
//
// Defaults to 30 minutes.
MaxTimeout time.Duration
}
type RealtimeMessageEvent struct {
+39 -1
View File
@@ -4,7 +4,7 @@ import (
"context"
"errors"
validation "github.com/go-ozzo/ozzo-validation/v4"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/tools/auth"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/types"
@@ -137,4 +137,42 @@ func (app *BaseApp) registerExternalAuthHooks() {
},
Priority: 99,
})
// delete all pre-existing external auths on verified upgrade
app.OnRecordUpdateExecute().Bind(&hook.Handler[*RecordEvent]{
Func: func(e *RecordEvent) error {
if !e.Record.Collection().IsAuth() {
return e.Next()
}
hasUpgradedVerified := !e.Record.Original().IsNew() && !e.Record.Original().Verified() && e.Record.Verified()
if !hasUpgradedVerified {
return e.Next()
}
originalApp := e.App
return e.App.RunInTransaction(func(txApp App) error {
e.App = txApp
defer func() { e.App = originalApp }()
externalAuths, err := txApp.FindAllExternalAuthsByRecord(e.Record)
if err != nil {
return err
}
if len(externalAuths) > 0 {
// delete all pre-existing external auths
if err := txApp.DeleteAllExternalAuthsByRecord(e.Record); err != nil {
return err
}
// force refresh tokens reset (if not already)
e.Record.RefreshTokenKey()
}
return e.Next()
})
},
Priority: 99,
})
}
+101
View File
@@ -308,3 +308,104 @@ func TestExternalAuthValidateHook(t *testing.T) {
})
}
}
func TestExternalAuthClearOnVerfiedUpgrade(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
t.Run("unverified->no changes", func(t *testing.T) {
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
if user.Verified() {
t.Fatal("Expected user to be unverified")
}
beforeAuths, err := app.FindAllExternalAuthsByRecord(user)
if err != nil || len(beforeAuths) == 0 {
t.Fatalf("Expected at least one external auth (%v)", err)
}
oldTokenKey := user.TokenKey()
if err = app.Save(user); err != nil {
t.Fatal(err)
}
if oldTokenKey != user.TokenKey() {
t.Fatal("Expected tokenKey to remain unchanged")
}
afterAuths, err := app.FindAllExternalAuthsByRecord(user)
if err != nil || len(afterAuths) != len(beforeAuths) {
t.Fatalf("Expected %d external auths, found %d (%v)", len(afterAuths), len(beforeAuths), err)
}
})
t.Run("unverified->verified", func(t *testing.T) {
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
if user.Verified() {
t.Fatal("Expected user to be unverified")
}
externalAuths, err := app.FindAllExternalAuthsByRecord(user)
if err != nil || len(externalAuths) == 0 {
t.Fatalf("Expected at least one external auth (%v)", err)
}
oldTokenKey := user.TokenKey()
user.SetVerified(true)
if err = app.Save(user); err != nil {
t.Fatal(err)
}
if oldTokenKey == user.TokenKey() {
t.Fatal("Expected tokenKey to be renewed")
}
externalAuths, err = app.FindAllExternalAuthsByRecord(user)
if err != nil || len(externalAuths) != 0 {
t.Fatalf("Expected all user external auths to be deleted, found %d (%v)", len(externalAuths), err)
}
})
t.Run("verified->no changes", func(t *testing.T) {
user, err := app.FindAuthRecordByEmail("users", "test3@example.com")
if err != nil {
t.Fatal(err)
}
if !user.Verified() {
t.Fatal("Expected user to be verified")
}
beforeAuths, err := app.FindAllExternalAuthsByRecord(user)
if err != nil || len(beforeAuths) == 0 {
t.Fatalf("Expected at least one external auth (%v)", err)
}
oldTokenKey := user.TokenKey()
if err = app.Save(user); err != nil {
t.Fatal(err)
}
if oldTokenKey != user.TokenKey() {
t.Fatal("Expected tokenKey to remain unchanged")
}
afterAuths, err := app.FindAllExternalAuthsByRecord(user)
if err != nil || len(afterAuths) != len(beforeAuths) {
t.Fatalf("Expected %d external auths, found %d (%v)", len(afterAuths), len(beforeAuths), err)
}
})
}
+24
View File
@@ -1,6 +1,8 @@
package core
import (
"errors"
"github.com/pocketbase/dbx"
)
@@ -59,3 +61,25 @@ func (app *BaseApp) FindFirstExternalAuthByExpr(expr dbx.Expression) (*ExternalA
return model, nil
}
// DeleteAllExternalAuthsByRecord deletes all ExternalAuth models associated with the provided record.
//
// Returns a combined error with the failed deletes.
func (app *BaseApp) DeleteAllExternalAuthsByRecord(authRecord *Record) error {
models, err := app.FindAllExternalAuthsByRecord(authRecord)
if err != nil {
return err
}
var errs []error
for _, m := range models {
if err := app.Delete(m); err != nil {
errs = append(errs, err)
}
}
if len(errs) > 0 {
return errors.Join(errs...)
}
return nil
}
+66
View File
@@ -2,6 +2,7 @@ package core_test
import (
"fmt"
"slices"
"testing"
"github.com/pocketbase/dbx"
@@ -174,3 +175,68 @@ func TestFindFirstExternalAuthByExpr(t *testing.T) {
})
}
}
func TestDeleteAllExternalAuthsByRecord(t *testing.T) {
t.Parallel()
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
demo1, err := testApp.FindRecordById("demo1", "84nmscqy84lsi1t")
if err != nil {
t.Fatal(err)
}
user1, err := testApp.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
client1, err := testApp.FindAuthRecordByEmail("clients", "test@example.com")
if err != nil {
t.Fatal(err)
}
client2, err := testApp.FindAuthRecordByEmail("clients", "test2@example.com")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
record *core.Record
deletedIds []string
}{
{demo1, nil}, // non-auth record
{user1, []string{"dlmflokuq1xl342", "clmflokuq1xl341"}},
{client1, []string{"f1z5b3843pzc964"}},
{client2, nil},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s_%s", i, s.record.Collection().Name, s.record.Id), func(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
deletedIds := []string{}
app.OnRecordDelete().BindFunc(func(e *core.RecordEvent) error {
deletedIds = append(deletedIds, e.Record.Id)
return e.Next()
})
err := app.DeleteAllExternalAuthsByRecord(s.record)
if err != nil {
t.Fatal(err)
}
if len(deletedIds) != len(s.deletedIds) {
t.Fatalf("Expected deleted ids\n%v\ngot\n%v", s.deletedIds, deletedIds)
}
for _, id := range s.deletedIds {
if !slices.Contains(deletedIds, id) {
t.Errorf("Expected to find deleted id %q in %v", id, deletedIds)
}
}
})
}
}
+21 -1
View File
@@ -6,7 +6,7 @@ import (
"regexp"
"strings"
validation "github.com/go-ozzo/ozzo-validation/v4"
validation "github.com/pocketbase/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core/validators"
"github.com/pocketbase/pocketbase/tools/list"
)
@@ -184,6 +184,26 @@ type RecordInterceptor interface {
) error
}
// DefaultFieldHelpValidationRule performs base validation on a field's "help" value.
func DefaultFieldHelpValidationRule(value any) error {
v, ok := value.(string)
if !ok {
return validators.ErrUnsupportedValueType
}
rules := []validation.Rule{
validation.Length(1, 300),
}
for _, r := range rules {
if err := r.Validate(v); err != nil {
return err
}
}
return nil
}
// DefaultFieldIdValidationRule performs base validation on a field id value.
func DefaultFieldIdValidationRule(value any) error {
v, ok := value.(string)

Some files were not shown because too many files have changed in this diff Show More