Compare commits

..
387 Commits
Author SHA1 Message Date
chashintv e2af9c4978 MSP-8974 fix 2026-11-23 13:27:39 +03:00
chashintv 24a8ea2578 MSP-8974 fix 2026-11-23 13:00:25 +03:00
chashintv ebc99c6ae4 MSP-8974 remove unused structs 2026-11-23 13:00:03 +03:00
chashintv 7bac2e403f MSP-8974 review fixes 2026-11-23 13:00:03 +03:00
chashintv 1ea3ef186c MSP-8974 up swagger 2026-11-23 13:00:03 +03:00
chashintv 1d1c5dbde6 MSP-8974 lint fixes 2026-11-23 13:00:03 +03:00
chashintv 11ef48bbeb MSP-8974 up deps 2026-11-23 13:00:01 +03:00
chashintv 5263e1504d MSP-8974 Bump version to 7.2.0 2026-11-23 12:59:29 +03:00
chashintv 06acaba5b3 MSP-8974 add download flow test 2026-11-23 12:58:54 +03:00
chashintv 2f29af5e76 MSP-8974 update doc 2026-11-23 12:58:54 +03:00
chashintv 3e707244dd MSP-8974 fix tests for http 2026-11-23 12:58:51 +03:00
chashintv fa8bc6c1b7 MSP-8974 fix tests 2026-11-23 12:58:04 +03:00
chashintv 71498785ea MSP-8974 add download flow, server migration to http 2026-11-23 12:54:59 +03:00
Иван Перлов aa68f6028a Merge branch 'MSP-8976' into 'dev'
Resolve MSP-8976

See merge request isp/isp-admin-service!5
2026-11-20 17:23:21 +03:00
Иван Перлов 11d705124d MSP-8976 Up deps 2026-11-20 17:19:44 +03:00
Иван Перлов b8ef777339 MSP-8976 Bump version to 7.2.0 2026-11-20 17:19:44 +03:00
Иван Перлов 7589203719 MSP-8976 Add application_group field and filter 2026-11-20 17:19:38 +03:00
Иван Перлов 67e9b563b4 MSP-8976 Up Go version to 1.27, linter conf 2026-11-18 16:02:49 +03:00
komissarovyv bca4b4adaf Remove github worflow 2026-09-10 14:17:58 +03:00
komissarovyv 14224c2de5 Edit README.md 2026-09-10 14:11:38 +03:00
komissarovyv 4e01670ceb Merge branch 'dev' into 'main'
Dev

Closes MSP-8520, MSP-8292, and MSP-8172

See merge request isp/isp-admin-service!2
2026-09-04 10:20:35 +03:00
komissarovyv e0a35868af Merge branch 'MSP-8520' into 'dev'
Resolve MSP-8520

See merge request isp/isp-admin-service!1
2026-09-04 10:18:19 +03:00
Павел Комиссаров 888a71df57 MSP-8520 restore blitz 2026-09-04 10:16:07 +03:00
Павел Комиссаров 4fecfaa701 MSP-8520 rename msp to isp and change errors package to isp 2026-09-04 10:16:07 +03:00
Павел Комиссаров 884aa6a439 MSP-8520 up deps 2026-09-03 18:05:39 +03:00
Павел Комиссаров c14f8441fb MSP-8520 bump version to 7.1.0 2026-09-03 18:04:52 +03:00
Павел Комиссаров 5bd389757c MSP-8520 rename sudir to oauth 2026-09-03 18:04:52 +03:00
Синельник Тимур Романович c32459f73d Merge branch 'MSP-8292' into 'dev'
Resolve MSP-8292

See merge request isp/msp-admin-service!23
2026-08-14 14:48:35 +03:00
Синельник Тимур Романович 911a5bdf46 MSP-8292 Bump changelog 2026-08-12 16:25:37 +03:00
Синельник Тимур Романович 3ee480f5e3 MSP-8292 Add ui_settings/sudir 2026-08-12 16:25:37 +03:00
Синельник Тимур Романович 5daaea50a1 MSP-8292 Up deps 2026-08-12 16:00:30 +03:00
Синельник Тимур Романович 3a66223a89 Merge branch 'MSP-8172' into 'dev'
Resolve MSP-8172

See merge request isp/msp-admin-service!22
2026-07-29 13:01:37 +03:00
Синельник Тимур Романович 674dd99f92 MSP-8172 Bump version to 7.0.0 2026-07-29 12:52:27 +03:00
Синельник Тимур Романович eb066cb055 MSP-8172 Add vendor 2026-07-29 12:52:27 +03:00
Синельник Тимур Романович 5175d87e08 MSP-8172 Check sudirAuth != nil before upgrade global request config 2026-07-29 12:30:10 +03:00
Синельник Тимур Романович 1db559469f MSP-8172 Keep 1 example for hex color 2026-07-29 11:50:20 +03:00
Синельник Тимур Романович 84c3529a66 MSP-8172 Add swagger structure fields comments 2026-07-28 16:44:08 +03:00
Синельник Тимур Романович 896f08a8cb MSP-8172 Up remote schema comments 2026-07-28 16:43:33 +03:00
Синельник Тимур Романович 86e96b79b1 MSP-8172 Up constructor for assembly 2026-07-28 15:52:51 +03:00
Синельник Тимур Романович f23359dfcb MSP-8172 Remove required tag for safe module migration 2026-07-28 15:52:51 +03:00
Синельник Тимур Романович ea81d2716f MSP-8172 context.Background() -> s.T().Context() 2026-07-28 15:52:51 +03:00
Синельник Тимур Романович e43a27e5d3 MSP-8172 Up remote config for sudir auth & logic for /auth/login_with_sudir 2026-07-28 15:52:51 +03:00
Синельник Тимур Романович f122ad081b MSP-8172 Rename http client & use base url 2026-07-28 15:52:51 +03:00
Синельник Тимур Романович 81c8e86eb4 MSP-8172 Up deps 2026-07-28 15:52:50 +03:00
Синельник Тимур Романович d81961e9d6 MSP-8172 Add swagger endpoint 2026-07-28 15:52:50 +03:00
komissarovyv 45bc24711e Merge branch '__deps' into 'main'
Update dependencies

See merge request isp/msp-admin-service!20
2026-07-27 16:27:00 +03:00
komissarovyv c9ce1158ea Update dependencies 2026-07-27 16:26:59 +03:00
komissarovyv b1c4322c98 Merge branch 'MSP-8007' into 'main'
Resolve MSP-8007

Closes MSP-8007

See merge request isp/msp-admin-service!19
2026-07-07 10:19:22 +03:00
kochanovrv 5625f00174 MSP-8007 up version to v6.8.1 2026-07-06 17:00:36 +03:00
kochanovrv f2c3f9dea5 MSP-8007 update isp-kit 2026-07-06 16:59:40 +03:00
Банченко Алексей Александрович 2d7adad800 Merge branch 'hot_fix_tests' into 'main'
Hot fix tests

See merge request isp/msp-admin-service!18
2026-03-23 14:05:04 +00:00
Банченко Алексей Александрович 939a94b704 Hot fix tests 2026-03-23 14:05:04 +00:00
Банченко Алексей Александрович bbeb6eb735 Merge branch 'MSP-7343' into 'main'
Resolve MSP-7343

Closes MSP-7343

See merge request isp/msp-admin-service!17
2026-03-23 13:01:39 +00:00
Банченко Алексей Александрович 5ee5854831 Resolve MSP-7343 2026-03-23 13:01:39 +00:00
Лихачев Алексей Михайлович 5ee9d85682 Merge branch 'MSP-7036' into 'main'
MSP-7036

See merge request isp/msp-admin-service!16
2026-02-16 13:24:32 +00:00
likhachevam 0442513f43 MSP-7036 up version to v6.7.0 2026-02-13 18:51:38 +03:00
likhachevam 69664d764a MSP-7036 fix name updating 2026-02-13 18:50:14 +03:00
likhachevam 67ff6571be MSP-7036 add user fullName 2026-02-13 17:06:52 +03:00
likhachevam a2c5dab4a7 MSP-7036 fix search by user.Id 2026-02-13 17:06:52 +03:00
likhachevam d2da566f25 MSP-7036 fix db deadlock when test ends 2026-02-13 17:06:52 +03:00
likhachevam d19bb44bb6 MSP-7036 refactor 2026-02-13 17:06:52 +03:00
likhachevam c036063534 MSP-7036 add expireSession worker 2026-02-13 17:06:52 +03:00
likhachevam ec327424c9 MSP-7036 fix search & sort 2026-02-13 17:06:52 +03:00
likhachevam 71e0768231 MSP-7036 add default sorting 2026-02-13 17:06:52 +03:00
likhachevam 4da0d51b5b MSP-7036 fix test races 2026-02-13 17:06:52 +03:00
likhachevam 1976e3aa29 MSP-7036 update docs 2026-02-13 17:06:52 +03:00
likhachevam 07540b762e MSP-7036 update dependencies 2026-02-13 17:06:52 +03:00
likhachevam 641aef0150 MSP-7036 update tests 2026-02-13 17:06:52 +03:00
likhachevam c17970678b MSP-7036 update pages sorting & search 2026-02-13 17:06:52 +03:00
likhachevam b1d5aae316 up alpine version 2026-02-13 17:05:56 +03:00
komissarovyv 2637770d82 Merge branch 'MSP-6636' into 'main'
Resolve MSP-6636

Closes MSP-6636

See merge request isp/msp-admin-service!15
2025-10-29 15:08:05 +03:00
kochanovrv 051c2f08c4 MSP-6636 up version to v6.6.1 2025-10-29 12:32:05 +03:00
kochanovrv 7de82862bd MSP-6636 add roleNames to get_profile method 2025-10-29 12:29:32 +03:00
Лихачев Алексей Михайлович 187e1f07a0 Merge branch 'MSP-6612' into 'main'
MSP-6612

See merge request isp/msp-admin-service!14
2025-10-27 12:13:01 +00:00
likhachevam f693afee79 MSP-6612 up version to v6.6.0 2025-10-27 13:52:53 +03:00
likhachevam d489c4281e MSP-6612 up go version 2025-10-27 13:52:46 +03:00
likhachevam e11f65ac05 MSP-6612 update docs 2025-10-27 12:55:43 +03:00
likhachevam 41ce47f7e0 MSP-6612 update dependencies 2025-10-27 12:54:28 +03:00
likhachevam 09dbce4125 MSP-6612 add 'user_blocked' audit event 2025-10-27 12:51:29 +03:00
Рябов Владислав Олегович 20f3fb7b5e Merge branch 'MSP-6168' into 'main'
MSP-6168

Closes MSP-6148

See merge request isp/msp-admin-service!12
2025-09-16 13:58:48 +00:00
Рябов Владислав Олегович a18deb8762 Merge branch 'MSP-6148' into 'MSP-6168'
Resolve MSP-6148

See merge request isp/msp-admin-service!13
2025-09-16 13:35:14 +00:00
yakovlevav 72b37d77e2 MSP-6148 up version to 6.5.0 2025-09-16 16:26:16 +03:00
yakovlevav 494ffac97c MSP-6148 add idle logout 2025-09-16 16:25:54 +03:00
likhachevam 841c75b457 MSP-6168 up version to v6.5.0 2025-09-16 16:25:30 +03:00
riabovvo fbd64f9d47 MSP-6168 update user logic 2025-09-16 16:25:30 +03:00
likhachevam 9b09326317 MSP-6168 add migration to change user unique fields 2025-08-29 18:16:05 +03:00
Грязнов Денис Владимирович 601a690901 Merge branch 'MSP-6078' into 'main'
Resolve MSP-6078

Closes MSP-6078

See merge request isp/msp-admin-service!11
2025-08-21 12:02:05 +00:00
Кузнецов Иван Александрович 4947ac5d4e MSP-6078 bump version to 6.4.0 2025-08-21 14:47:58 +03:00
Кузнецов Иван Александрович df693c0294 MSP-6078 update deps 2025-08-21 14:46:10 +03:00
Рябов Владислав Олегович 3f65b11a65 Merge branch 'MSP-6038' into 'main'
Resolve MSP-6038

Closes MSP-6038

See merge request isp/msp-admin-service!10
2025-08-11 08:57:57 +00:00
riabovvo 38f22dfdf8 MSP-6038 bump version to 6.3.1 2025-08-11 11:48:15 +03:00
riabovvo 302e9b7a54 MSP-6038 update test for changes 2025-08-11 11:47:50 +03:00
riabovvo 996abfda16 MSP-6038 update repo host path for methods 2025-08-11 11:47:42 +03:00
komissarovyv fb882e5c5c Merge branch 'MSP-5083' into 'main'
Resolve MSP-5083

Closes MSP-5083 and MSP-5052

See merge request isp/msp-admin-service!8
2025-07-25 15:07:49 +03:00
Яковлев Алексей Владимирович 3a2ad9219c Merge branch 'MSP-5052' into 'MSP-5083'
Resolve MSP-5052

See merge request isp/msp-admin-service!9
2025-07-25 11:51:50 +00:00
yakovlevav 7514be3309 MSP-5052 up version to 6.3.0 2025-07-25 10:35:06 +03:00
yakovlevav 4f67872d3f MSP-5052 remove ldap 2025-07-25 10:35:06 +03:00
yakovlevav 558682da1e MSP-5083 fix blocking user 2025-07-25 10:33:53 +03:00
Рябов Кирилл Александрович 40b37f8900 Merge branch 'MSP-5494' into 'main'
MSP-5494

See merge request isp/msp-admin-service!7
2025-05-27 19:07:04 +07:00
Kirill Ryabov 4791c6dbaf MSP-5494 bump version to 6.2.6 2025-05-27 14:03:20 +03:00
Kirill Ryabov 05ac07c3bb MSP-5494 update dependencies 2025-05-27 14:03:20 +03:00
Kirill Ryabov 4cc5edeed0 MSP-5494 add Dockerfile 2025-05-27 14:03:20 +03:00
Kirill Ryabov 830ef54663 MSP-5494 add github actions ci to build & publish docker image 2025-05-26 14:44:09 +03:00
Рябов Кирилл Александрович 0cb61c184a Merge branch 'MSP-3073' into 'main'
MSP-3073

See merge request isp/msp-admin-service!6
2025-05-13 22:06:00 +07:00
Kirill Ryabov e9030f6282 MSP-3073 bump version to 6.2.5 2025-05-13 16:52:02 +03:00
Kirill Ryabov 51081ca964 MSP-3073 update swagger 2025-05-13 16:52:02 +03:00
Kirill Ryabov cb59605eba MSP-3073 update dependencies 2025-05-13 15:55:57 +03:00
Kirill Ryabov d7779efdbd MSP-3073 migrate golangci-lint to v2 2025-05-13 15:52:27 +03:00
Kirill Ryabov b89e10a0bd MSP-3073 fix panic cause empty slice access 2025-05-13 15:51:54 +03:00
Грязнов Денис Владимирович 9bf05f1e9d Merge branch 'MSP-5320' into 'main'
Update dependencies

See merge request isp/msp-admin-service!5
2025-04-23 09:40:22 +00:00
Парусов Павел Андреевич 8f80bf5742 MSP-5320 update dependencies 2025-04-23 11:00:21 +03:00
Кузьмин Игорь Александрович 1746acd559 Add new file 2025-04-18 09:56:20 +00:00
Кузьмин Игорь Александрович b16ac80053 Replace .gitlab-ci.yml 2025-04-18 09:24:30 +00:00
komissarovyv 635046d221 Merge branch 'MSP-5093' into 'main'
Resolve MSP-5093

Closes MSP-5093

See merge request isp/msp-admin-service!4
2025-03-26 08:33:00 +00:00
komissarovyv 46fc51275e MSP-5093 remove global varibale 2025-03-26 11:28:43 +03:00
komissarovyv 055921d711 MSP-5093 bump version to 6.2.1 2025-03-26 11:28:41 +03:00
komissarovyv bf8cfff7fa MSP-5093 bump dependencies 2025-03-26 11:28:12 +03:00
komissarovyv 3be63ce95a MSP-5093 add default permissions 2025-03-26 11:27:46 +03:00
Грязнов Денис Владимирович f5a38117b1 Merge branch 'MSP-5004' into 'main'
Update dependencies

See merge request isp/msp-admin-service!2
2025-03-03 08:19:48 +00:00
Кузнецов Иван Александрович 21714e0603 MSP-5004 update dependencies 2025-02-27 20:47:56 +03:00
Кузьмин Игорь Александрович c966a2cca5 Upload New File 2024-12-27 15:20:12 +00:00
Кузьмин Игорь Александрович c2f154da02 Upload New File 2024-12-27 15:19:58 +00:00
foxxy 2343940930 bump version to 6.2.1 2024-12-11 12:33:51 +03:00
komissarovyv 2d6398224f Delete unused permission 2024-11-15 14:17:19 +03:00
komissarovyv ac1457e534 Add missing user_view permission 2024-11-15 13:35:17 +03:00
komissarovyv b59a5ce858 Bump dependencies 2024-10-28 14:05:03 +03:00
d1slike 4352c400b4 Add new admin permission to default remote config 2024-06-28 14:01:55 +03:00
d1slike 1653289e01 Try to fix flaky inactive user test 2024-06-28 13:31:52 +03:00
d1slike cf20571a7d Add new permissions 2024-06-28 13:25:56 +03:00
komissarovyv e4755abdc8 Merge branch 'MSP-3427' into 'main'
Resolve MSP-3427

Closes MSP-3427

See merge request isp/msp-admin-service!1
2024-06-20 07:42:27 +00:00
Tim e7935499b6 MSP-3427 added audit for password change 2024-06-19 12:37:43 +03:00
Tim 6f48eea3c9 MSP-3427 removed docs.go 2024-06-18 14:28:35 +03:00
Tim 4251ca3da9 MSP-3427 added logout after password change 2024-06-18 14:12:15 +03:00
Tim 3a564dfae8 MSP-3427 gitignore config_dev.yml 2024-06-18 13:39:22 +03:00
Tim c4871f210d MSP-3427 removed config_dev.yml 2024-06-17 17:18:05 +03:00
Tim fcebffe4b6 MSP-3427 removed patch 2024-06-17 12:30:29 +03:00
Tim a741135dc3 MSP-3427 up version to 6.1.1 2024-06-13 19:52:50 +03:00
Tim 7d60f6d51d MSP-3427 fixed typo 2024-06-13 18:20:01 +03:00
Tim fb0a08ea13 MSP-3427 remote_test.go fixes 2024-06-13 18:12:14 +03:00
Tim 10e316049d MSP-3427 minor fixes in user.test 2024-06-13 18:00:05 +03:00
Tim 753af57524 MSP-3427 swagger refreshed 2024-06-13 17:51:07 +03:00
Tim 1f232c4271 MSP-3427 linter fixes 2024-06-13 17:08:10 +03:00
Tim a7ec10fa39 MSP-3427 updated golangci.yml 2024-06-13 16:47:43 +03:00
Tim d799b5be60 MSP-3427 password change realized 2024-06-13 16:45:37 +03:00
Tim 03bbdd1761 MSP-3427 golang -> 1.22 2024-06-11 12:03:33 +03:00
Кузьмин Игорь Александрович 72a62d1996 Delete Dockerfile.dit 2024-03-25 13:18:22 +00:00
Кузьмин Игорь Александрович 3552e08f29 Delete .gitlab-ci.yml 2024-03-25 13:18:16 +00:00
komissarovyv c2e7c5ab2b Merge branch 'MSP-2370' into 'main'
MSP-2370 implement admin/secure/authorize

Closes MSP-2370

See merge request msp2.0/msp-admin-service!21
2023-11-15 10:48:30 +00:00
d1slike 3b3fc9dcfb MSP-2370 implement admin/secure/authorize 2023-11-14 17:04:42 +03:00
Кузьмин Игорь db7a668875 Delete .kkd-ci.yml 2023-11-09 13:36:55 +00:00
komissarovyv a4b3bfa390 Merge branch 'MSP-2171' into 'master'
Resolve MSP-2171

Closes MSP-2171

See merge request msp2.0/msp-admin-service!20
2023-10-24 16:12:04 +00:00
d1slike c77ab9d5f8 MSP-2175 handle no action required error 2023-10-24 19:09:12 +03:00
d1slike e65f5ac03c MSP-2175 align func naming 2023-10-24 11:02:51 +03:00
d1slike c08782855b MSP-2175 implement ldap sync 2023-10-23 20:04:33 +03:00
Кузьмин Игорь a5a4dab813 Upload New File 2023-10-19 14:22:47 +00:00
d1slike 03a7b16026 Trigger deploy 2023-10-18 13:52:46 +03:00
komissarovyv 9a12e08181 Merge branch 'MSP-2243' into 'master'
Resolve MSP-2243

Closes MSP-2243

See merge request msp2.0/msp-admin-service!19
2023-10-18 10:29:46 +00:00
d1slike cd04e996e1 MSP-2243 implement ldap integration 2023-10-18 13:24:50 +03:00
d1slike 051dea1674 MSP-2243 Fix metric collecting 2023-10-18 13:24:50 +03:00
gr-dv c1263fce77 MSP-2243 update version 2023-10-18 13:24:50 +03:00
gr-dv f3bc3ce657 MSP-2243 update linter 2023-10-18 13:24:50 +03:00
gr-dv 3beb23d4de MSP-2243 update dependencies 2023-10-18 13:24:50 +03:00
gr-dv 3f177eb436 MSP-2243 update swagger 2023-10-18 13:24:49 +03:00
gr-dv df15ae228a MSP-2243 update role 2023-10-18 13:24:48 +03:00
gr-dv 61bdaeaa3d MSP-2243 add migration update roles table 2023-10-18 13:24:47 +03:00
gr-dv 03580260e7 MSP-2243 add audit_event test 2023-10-18 13:24:47 +03:00
gr-dv cf42bed9bf MSP-2243 update assembly 2023-10-18 13:24:47 +03:00
gr-dv c4c0f2ea10 MSP-2243 implement delete old_audit_worker 2023-10-18 13:24:47 +03:00
gr-dv c1d4680a02 MSP-2243 update interface 2023-10-18 13:24:47 +03:00
gr-dv 1517f744d3 MSP-2243 add new method in audit service 2023-10-18 13:24:47 +03:00
gr-dv 6af7ed9cb8 MSP-2243 update old method in audit service 2023-10-18 13:24:47 +03:00
gr-dv 5cff5df97b MSP-2243 update remote config 2023-10-18 13:24:47 +03:00
gr-dv d208ad633e MSP-2243 add delete method to audit repository 2023-10-18 13:24:47 +03:00
gr-dv a664d5db4a MSP-2243 add event field to audit repository 2023-10-18 13:24:47 +03:00
gr-dv 7b5e1362be MSP-2243 add audit_event repository 2023-10-18 13:24:47 +03:00
gr-dv b2305c0f12 MSP-2243 add migration: bgjob 2023-10-18 13:24:47 +03:00
gr-dv 73ab09dc7d MSP-2243 add migration: create audit_event table 2023-10-12 11:10:10 +03:00
gr-dv 150d61fb18 MSP-2243 update audit controller: add new methods 2023-10-12 11:10:10 +03:00
Кузьмин Игорь 158962dcfe Update .gitlab-ci.yml 2023-06-07 06:51:00 +00:00
Рябов Владислав Олегович 41479adbb0 Merge branch 'MSP-1756' into 'master'
Resolve MSP-1756

Closes MSP-1756

See merge request msp2.0/msp-admin-service!18
2023-05-26 10:01:25 +00:00
riabovvo 2c1c655fed MSP-1756 update user service 2023-05-25 13:59:20 +03:00
riabovvo 669542b546 MSP-1756 remove last session field in user entity and repo 2023-05-25 13:59:06 +03:00
riabovvo 92021b8a0e MSP-1756 get new method for token repository 2023-05-25 13:58:19 +03:00
riabovvo 1bbe8c71ce MSP-1756 update auth service (remove last session update) 2023-05-25 13:57:37 +03:00
riabovvo 98b79732fa MSP-1756 update schema migration 2023-05-25 13:57:05 +03:00
d1slike d2f56ca43e MSP-1756 reimplement 2023-05-25 12:38:36 +03:00
riabovvo 6fcc9e45e3 MSP-1756 remove last session in crud 2023-05-25 11:43:33 +03:00
riabovvo 7f7a827a69 MSP-1756 update sudir auth role management 2023-05-23 20:36:29 +03:00
riabovvo a915bdf633 MSP-1756 update error context 2023-05-23 20:36:29 +03:00
riabovvo ef0028c091 MSP-1756 remove last session in crud 2023-05-23 20:36:29 +03:00
riabovvo 4cad9cbbb4 MSP-1756 update sudir service 2023-05-23 20:32:04 +03:00
riabovvo 7f7216b91a MSP-1756 update role repo 2023-05-23 20:32:04 +03:00
riabovvo 7e899197ec MSP-1756 update role entity 2023-05-23 20:32:04 +03:00
riabovvo c25d6e3d3b MSP-1756 update swagger 2023-05-23 20:32:04 +03:00
riabovvo da3ae21766 MSP-1756 update audit 2023-05-23 20:32:04 +03:00
riabovvo 84888e8202 MSP-1756 update migration 2023-05-23 20:32:04 +03:00
riabovvo cccb1fc80b MSP-1756 add merge permissions, update permissions service 2023-05-23 12:43:28 +03:00
riabovvo d3747e6ff3 MSP-1756 update tests 2023-05-22 18:41:30 +03:00
riabovvo 036200a765 MSP-1756 add transactional 2023-05-22 18:25:03 +03:00
riabovvo fa89426bcc MSP-1756 add audit 2023-05-22 18:24:00 +03:00
riabovvo 8a2752fdaa MSP-1756 up version 2023-05-22 14:04:12 +03:00
riabovvo efc521f8fe MSP-1756 update tests 2023-05-22 14:04:03 +03:00
riabovvo dbf35fc383 MSP-1756 update locator 2023-05-22 14:03:48 +03:00
riabovvo 6e9918dc7b MSP-1756 update routes 2023-05-22 14:03:37 +03:00
riabovvo b21154afd7 MSP-1756 update auth services 2023-05-22 14:03:21 +03:00
riabovvo 234ea0ca38 MSP-1756 update user 2023-05-22 14:03:02 +03:00
riabovvo e81028722f MSP-1756 implement user_roles repo 2023-05-22 14:02:43 +03:00
riabovvo 557491ed05 MSP-1756 implement roles (as a service) 2023-05-22 14:02:11 +03:00
riabovvo 1e6c72ead2 MSP-1756 add permissions 2023-05-22 14:01:11 +03:00
riabovvo bcf3fd576a MSP-1756 add migration 2023-05-22 13:59:47 +03:00
Кузьмин Игорь fa3d8f5f14 Upload New File 2023-05-10 08:50:54 +00:00
Кузьмин Игорь 74625d0525 Upload New File 2023-05-10 08:50:28 +00:00
komissarovyv a355338d40 Merge branch 'MSP-1538' into 'master'
Resolve MSP-1538

Closes MSP-1538

See merge request msp2.0/msp-admin-service!17
2023-04-17 08:16:02 +00:00
gr-dv 60fc5d9170 MSP-1658 /user/get_profile returning 401 for blocked users 2023-04-10 14:12:24 +03:00
d1slike 0877e05811 MSP-1538 use GivenName as role id 2023-04-05 18:12:40 +03:00
d1slike abcf2162a7 MSP-1538 bump version 2023-03-30 10:41:38 +03:00
d1slike 0cea0d4f0a MSP-1538 add new controllers 2023-03-30 10:41:38 +03:00
d1slike 205c4724d4 MSP-1538 regenerate swagger 2023-03-30 10:41:38 +03:00
d1slike 917982cff1 MSP-1538 bind new endpoints 2023-03-30 10:41:38 +03:00
d1slike 4d1c17f9ae MSP-1538 implement session api 2023-03-30 10:41:38 +03:00
d1slike 45810b4ec8 MSP-1538 implement audit api 2023-03-30 10:41:38 +03:00
d1slike fdd46409cd MSP-1538 implement inactive user blocker 2023-03-30 10:41:38 +03:00
d1slike 72e89b1c9f MSP-1538 reimplement user api 2023-03-30 10:41:38 +03:00
d1slike 060c5a09de MSP-1538 add db migration 2023-03-27 10:30:42 +03:00
d1slike 0d5b55f3a1 MSP-1538 upgrade dependencies 2023-03-27 10:28:06 +03:00
Поляков Евгений Александрович 3d29805df6 Merge branch 'MSP-1071' into 'master'
Resolve MSP-1071

Closes MSP-1071

See merge request msp2.0/msp-admin-service!15
2022-10-12 09:14:28 +00:00
john 2561479816 MSP-1071 add anti bruteforce test 2022-10-12 09:12:38 +03:00
john 447d33747a MSP-1071 update locator 2022-10-12 09:12:38 +03:00
john 56e38174bf MSP-1071 add error to admin login in controller 2022-10-12 09:12:38 +03:00
john f90f21ebef MSP-1071 add anti bruteforce in admin login 2022-10-12 09:12:38 +03:00
john c6f5f4096b MSP-1071 add login error request 2022-10-12 09:12:38 +03:00
john d2a1b2394b MSP-1071 update remote config 2022-10-12 09:12:38 +03:00
john 0a2eab739e MSP-1071 up version 2022-10-12 09:12:38 +03:00
john f26b953a3f MSP-1071 update mod sum 2022-10-11 14:59:26 +03:00
komissarovyv 882f6a47bf Merge branch 'fix_get_profile' into 'master'
Fix get profile

See merge request msp2.0/msp-admin-service!16
2022-10-10 15:45:11 +00:00
d1slike 2d3179180e Remove unused middleware 2022-10-10 18:42:05 +03:00
d1slike 5d6616652d Bump version 2022-10-10 18:38:56 +03:00
d1slike b349af7351 Translate all errors to english 2022-10-10 18:38:56 +03:00
d1slike c843bce25d Reimplement get_profile 2022-10-10 18:38:56 +03:00
komissarovyv 607539d47b Merge branch 'MSP-1070' into 'master'
Resolve MSP-1070

Closes MSP-1070

See merge request msp2.0/msp-admin-service!13
2022-10-10 14:51:27 +00:00
DeniskaRediska b2ec20421f MSP-1070 up version 2022-10-10 16:32:13 +03:00
DeniskaRediska 14d526e033 MSP-1070 update swagger 2022-10-10 16:32:13 +03:00
DeniskaRediska e2df3f377d MSP-1070 update dependencies 2022-10-10 16:32:13 +03:00
DeniskaRediska 670957db36 MSP-1070 add mapping error for get_profile 2022-10-10 16:32:13 +03:00
DeniskaRediska c1e4aded9d MSP-1070 add logout test 2022-10-10 16:32:13 +03:00
DeniskaRediska ca4554f514 MSP-1070 implement logout 2022-10-10 16:32:13 +03:00
DeniskaRediska 39911e3a09 MSP-1070 add secure/authenticate test 2022-10-10 16:32:13 +03:00
DeniskaRediska 17559ce3ba MSP-1070 add secure/authenticate method 2022-10-10 16:32:13 +03:00
DeniskaRediska b79ed21c10 MSP-1070 remove secret key 2022-10-10 16:32:13 +03:00
DeniskaRediska 850abfd93c MSP-1070 migrate token service to token repo 2022-10-10 16:26:08 +03:00
DeniskaRediska 5af15ed13a MSP-1070 add tokens table 2022-10-07 17:37:37 +03:00
DeniskaRediska d3ffa31e00 MSP-1070 add token rep errors 2022-10-07 17:00:29 +03:00
DeniskaRediska ece61a0e87 MSP-1070 rename auth struct to login struct 2022-10-07 17:00:29 +03:00
Новиков Михаил Юрьевич bb4c8cd8ad Merge branch 'MSP-1068_metadata_hotfix' into 'master'
Resolve MSP-1068 "Metadata hotfix"

Closes MSP-1068

See merge request msp2.0/msp-admin-service!14
2022-10-07 12:28:39 +00:00
novikovmu f54132443c MSP-1068 changelog 2022-10-07 15:18:39 +03:00
novikovmu 82009842a6 MSP-1068 fix user test: append metadata 2022-10-07 15:14:05 +03:00
novikovmu 312f4fbd24 MSP-1068 fix: get metadata with authdata type 2022-10-07 15:14:05 +03:00
novikovmu 8fa3be2d17 MSP-1068 update isp-kit 2022-10-07 15:14:05 +03:00
Новиков Михаил Юрьевич a7147a0c06 Merge branch 'hotfix/default-remote-config' into 'master'
Hotfix/default remote config

See merge request msp2.0/msp-admin-service!11
2022-10-07 08:35:55 +00:00
novikovmu b40c180471 changelog 2022-10-07 11:34:43 +03:00
novikovmu 1ab60e0a29 fix: default_remote_config.json 2022-10-07 11:34:34 +03:00
Новиков Михаил Юрьевич 68e15a3c78 Merge branch 'MSP-1068' into 'master'
Resolve MSP-1068

Closes MSP-1068

See merge request msp2.0/msp-admin-service!10
2022-10-07 08:09:08 +00:00
novikovmu c90721bb13 MSP-1068 init tests 2022-10-06 17:57:30 +03:00
novikovmu 0f368d304a MSP-1068 changelog 2022-10-06 17:57:30 +03:00
novikovmu a98d4db606 MSP-1068 update docs 2022-10-06 17:57:30 +03:00
novikovmu 848df1830f MSP-1068 refactor main 2022-10-06 17:57:30 +03:00
novikovmu a9485516b6 MSP-1068 init routes 2022-10-06 17:57:30 +03:00
novikovmu 4c3559bffd MSP-1068 init assembly 2022-10-06 17:57:30 +03:00
novikovmu 5f1d8c8fd4 MSP-1068 init error handler middleware 2022-10-06 17:57:30 +03:00
novikovmu 4e6b21a7d9 MSP-1068 refactor user controller 2022-10-06 17:57:30 +03:00
novikovmu 7be37bc52d MSP-1068 refactor customization controller 2022-10-06 17:57:30 +03:00
novikovmu 208dbe7b58 MSP-1068 init auth controller 2022-10-06 17:57:30 +03:00
novikovmu 193adeed9c MSP-1068 init user service 2022-10-06 17:14:09 +03:00
novikovmu 198f5633d4 MSP-1068 init auth service 2022-10-06 17:14:09 +03:00
novikovmu e2e8bf5f45 MSP-1068 init token service 2022-10-06 17:14:09 +03:00
novikovmu 932d5cb725 MSP-1068 init sudir service 2022-10-06 17:14:09 +03:00
novikovmu 5bb4da2650 MSP-1068 init user repository 2022-10-06 17:14:09 +03:00
novikovmu 2cf17a20d0 MSP-1068 init sudir repository 2022-10-06 17:14:09 +03:00
novikovmu f3accb56b5 MSP-1068 init role repository 2022-10-06 17:14:09 +03:00
novikovmu 9ecc52a8eb MSP-1068 move out socket service 2022-10-06 17:14:09 +03:00
novikovmu 27bc07fcd9 MSP-1068 move out model 2022-10-06 17:14:09 +03:00
novikovmu fcade81bf5 MSP-1068 move out invoker 2022-10-06 17:14:09 +03:00
novikovmu a720cef797 MSP-1068 move out helper 2022-10-06 17:14:09 +03:00
novikovmu abd9a937a1 MSP-1068 refactor entity 2022-10-06 17:14:09 +03:00
novikovmu 7feb2d6507 MSP-1068 refactor structure: make domain directory 2022-10-06 17:14:09 +03:00
novikovmu 06818e5616 MSP-1068 refactor config 2022-10-06 17:14:09 +03:00
novikovmu ca8d278566 MSP-1068 init golangci 2022-10-06 17:14:09 +03:00
novikovmu d3068c1947 MSP-1068 make sql users migration 2022-10-06 17:14:09 +03:00
novikovmu 4d6094b384 MSP-1068 upgrade dependencies 2022-10-05 18:07:44 +03:00
Грязнов Денис Владимирович 0ee80926ef Merge branch 'MSP-247_read_only_role' into 'master'
Msp 247 read only role

See merge request msp2.0/msp-admin-service!9
2021-08-26 09:43:42 +00:00
DeniskaRediska a72862f94e MSP-247 update version and changelog 2021-08-25 18:46:41 +03:00
DeniskaRediska 0e8afa6cd6 MSP-247 remove excess field tableName from response /user/get_profile 2021-08-25 18:46:36 +03:00
DeniskaRediska 5456e59f0b MSP-247 add role to response /user/get_profile 2021-08-25 18:45:30 +03:00
DeniskaRediska e2549ebffe MSP-247 add role check to get_profile 2021-08-25 18:43:07 +03:00
DeniskaRediska 23c6b16a7c MSP-247 add role link for sudir user 2021-08-25 18:43:00 +03:00
DeniskaRediska 5b61803868 MSP-247 add role repository 2021-08-25 18:38:38 +03:00
DeniskaRediska 07acc3b087 MSP-247 add role_id to user entity 2021-08-25 18:38:38 +03:00
DeniskaRediska d8f9a6940d MSP-247 fix sudir user response 2021-08-25 18:38:38 +03:00
DeniskaRediska 7bde532b31 MSP-247 add read_only_admin role 2021-08-25 18:37:32 +03:00
DeniskaRediska 12811d119a MSP-247 refactoring invoke sudir 2021-08-25 16:47:38 +03:00
DeniskaRediska 21ab57ddc2 MSP-247 refactoring move sudir "net/http" cli to inner http cli 2021-08-25 16:47:30 +03:00
DeniskaRediska 80880c2f69 MSP-247 refactoring sudir cli structs 2021-08-25 16:47:21 +03:00
DeniskaRediska 38d065ab86 MSP-247 refactoring move sudir cli to invoker folder 2021-08-25 16:47:04 +03:00
Мержанов Максим Владимирович 685520ef8d Merge branch '__deps' into 'master'
Update dependencies

See merge request msp2.0/msp-admin-service!8
2021-08-06 15:22:44 +00:00
Maxim Merzhanov 974eac515e Update dependencies 2021-08-06 18:16:18 +03:00
Мержанов Максим Владимирович 1db5a1a82e Merge branch 'sudir_login' into 'master'
implement login with SUDIR auth code

See merge request msp2.0/msp-admin-service!7
2021-07-06 11:15:57 +00:00
Мержанов Максим Владимирович dfc78ddc71 implement login with SUDIR auth code 2021-07-06 11:15:57 +00:00
Мержанов Максим Владимирович 6bac52cdea Merge branch '__deps' into 'master'
Update dependencies

See merge request msp2.0/msp-admin-service!6
2021-05-17 15:52:39 +00:00
Egor Kiryushchenko 48e310d4b0 Update dependencies 2021-05-17 16:25:09 +03:00
Мержанов Максим Владимирович bf6a8de246 Merge branch 'docs' into 'master'
add swagger docs, refactor

See merge request msp2.0/msp-admin-service!5
2021-02-10 13:50:12 +00:00
Рябов Владислав Олегович 416013ed1d add swagger docs, refactor 2021-02-10 16:50:12 +03:00
Мержанов Максим Владимирович f5ab9c768f Merge branch 'graceful_fix' into 'master'
fixed graceful shutdown

See merge request msp2.0/msp-admin-service!4
2021-02-08 12:11:41 +03:00
Рябов Владислав Олегович bbb9d200ce fixed graceful shutdown 2021-02-08 12:11:41 +03:00
Мержанов Максим Владимирович 2a53d5b19d Merge branch 'feature/customization' into 'master'
add ui customization method

See merge request msp2.0/msp-admin-service!3
2021-02-02 12:16:06 +03:00
Maxim Merzhanov 2135dfca96 rename customization -> design 2021-02-01 18:34:15 +03:00
Maxim Merzhanov 32ef7a7097 update config schema 2021-02-01 11:22:08 +03:00
Maxim Merzhanov faaa642b0b fix deprecated db tags 2021-01-29 12:45:57 +03:00
Maxim Merzhanov a5b8620e39 add ui customization method 2021-01-28 17:16:03 +03:00
Мержанов Максим Владимирович 724c25ecd6 Merge branch '__deps' into 'master'
Update dependencies

See merge request msp2.0/msp-admin-service!2
2021-01-26 18:54:33 +03:00
Egor Kiryushchenko 4091b62817 Update dependencies 2021-01-26 14:00:46 +03:00
Максим Мержанов 5cc4936962 Merge branch '__deps' into 'master'
Update dependencies

See merge request msp2.0/msp-admin-service!18
2020-11-24 14:28:21 +03:00
Егор Кирющенко 677c49216f Update dependencies 2020-11-24 14:28:21 +03:00
Максим Мержанов 251505f9f7 Merge branch 'upd_branch' into 'master'
update version

See merge request msp2.0/msp-admin-service!7
2020-11-05 13:28:33 +03:00
Рябов Владислав Олегович cccb276493 Обновить CHANGELOG.md, .version файлов 2020-11-05 13:21:04 +03:00
Максим Мержанов 495ff06bbe Merge branch 'rt_branch' into 'master'
Added real-time updates via websocket

See merge request msp2.0/msp-admin-service!6
2020-11-05 12:47:04 +03:00
Рябов Владислав Олегович 72b163e22d Added real-time updates via websocket 2020-11-05 12:47:03 +03:00
yan komissarov 3e77f00d16 Merge branch 'modules' into 'master'
migrate to go mod, up deps

See merge request msp2.0/msp-admin-service!5
2020-04-14 11:17:56 +03:00
merzhanovmv 00c43353f2 migrate to go mod, up deps 2020-04-10 16:21:20 +03:00
Jenkins Automation Server 82a3f877a7 Update dependencies 2020-01-09 19:13:40 +03:00
yan komissarov edf17d6434 Merge branch 'dev' into 'master'
Update dependencies

See merge request msp2.0/msp-admin-service!4
2019-11-21 12:53:26 +03:00
Максим Мержанов 7c1fd79af1 Update dependencies 2019-11-21 12:53:26 +03:00
yan komissarov c281fb1e01 Merge branch '2-default-remote-config' into 'master'
Resolve "default remote config"

Closes #2

See merge request msp2.0/msp-admin-service!2
2019-06-03 17:12:38 +03:00
gryaznovdv ddaf57df6c add(default remote config) 2019-06-03 16:57:45 +03:00
ykomissarov 011aaa50e8 reformat 2019-05-31 15:49:01 +03:00
ykomissarov 0d956b6bf6 fix get user by token method 2019-05-08 15:46:26 +03:00
yan komissarov 8f2a6a58f2 Merge branch '1-v2' into 'master'
Resolve "v2"

Closes #1

See merge request msp2.0/msp-admin-service!1
2019-05-08 13:06:48 +03:00
ykomissarov 24dc1fe615 ref 2019-05-08 13:06:08 +03:00
gryaznovdv dc5ca4b1c6 added migration 2019-05-07 18:05:01 +03:00
gryaznovdv 9884712392 changed token 2019-05-07 17:39:09 +03:00
ykomissarov 0c5b23b790 package refactoring 2019-03-20 11:25:20 +03:00
ykomissarov edd51c67c4 upd lib 2019-03-18 14:03:32 +03:00
ykomissarov 05341ad604 upd lib 2019-03-18 11:47:13 +03:00
ykomissarov 493f105055 add config shema 2019-01-18 17:58:50 +03:00
ykomissarov f5d46fcaba upd lib 2019-01-17 14:08:16 +03:00
Andrey Savchuk 8533f1aaad update lib 2019-01-16 15:04:52 +03:00
Andrey Savchuk 419c3799f6 update lib 2018-12-27 17:46:47 +03:00
Andrey Savchuk 00c0e4949b update lib 2018-12-25 18:15:52 +03:00
Andrey Savchuk 88fc42f8ec update lib 2018-12-12 18:54:06 +03:00
ykomissarov d28b0c09de new boot 2018-12-12 16:21:05 +03:00
ykomissarov 412a150d1e new boot 2018-12-11 15:56:44 +03:00
Andrey Savchuk 405f6f8cee update lib 2018-11-08 01:05:37 +03:00
Andrey Savchuk d8ca8e4116 update lib 2018-11-07 20:31:36 +03:00
Andrey Savchuk dcb2d5943d update lib 2018-10-13 16:07:58 +03:00
Andrey Savchuk 8da7fab51f update lib 2018-10-11 14:55:51 +03:00
Andrey Savchuk 8408f574a1 add metrics 2018-10-09 17:54:27 +03:00
andrey savchuk 973812230a Update Gopkg.lock 2018-09-13 16:56:45 +03:00
andrey savchuk 2c45cb2887 Update Gopkg.lock 2018-09-13 16:43:09 +03:00
andrey savchuk 1cd2b08524 Update 00005_2018-04-27_add_main_user.sql 2018-09-12 23:08:25 +03:00
Andrey Savchuk 61afe79506 Merge branch 'develop'
# Conflicts:
#	Gopkg.lock
2018-09-12 22:50:42 +03:00
Andrey Savchuk b97e82c2dd update lib 2018-09-12 22:48:37 +03:00
andrey savchuk d40d78d098 Update Gopkg.lock 2018-09-11 15:57:54 +03:00
ykomissarov 6e59ef4e8d change path 2018-09-04 15:53:21 +03:00
Andrey Savchuk d0f0642c45 change docker file 2018-08-12 01:26:39 +03:00
ykomissarov 577c1fd1a6 update libs 2018-08-07 10:50:53 +03:00
Andrey Savchuk 1b7eef2443 fix build script 2018-06-21 17:43:52 +03:00
Andrey Savchuk 6fc835dacb add inner address into config
change algorithm for creating method path
2018-06-20 13:16:52 +03:00
Andrey Savchuk 1cad4a158e add inner address into config
change algorithm for creating method path
2018-06-20 12:48:05 +03:00
Andrey Savchuk b0c9033c06 add inner address into config
change algorithm for creating method path
2018-06-20 12:47:25 +03:00
Andrey Savchuk b224f0d4a1 add inner address into config
change algorithm for creating method path
2018-06-20 12:46:23 +03:00
Andrey Savchuk b4d913d517 add inner address into config
change algorithm for creating method path
2018-06-20 12:44:25 +03:00
Andrey Savchuk c28e08d7a2 add inner address into config
change algorithm for creating method path
2018-06-20 12:44:06 +03:00
Andrey Savchuk 7b7bccbca2 add method get_profile 2018-06-15 19:39:30 +03:00
Andrey Savchuk 8c0513d394 add method logout
rename auth method to login
2018-06-15 18:56:38 +03:00
Andrey Savchuk 7ab0e77a97 update libraries and versioning 2018-06-14 16:32:53 +03:00
Andrey Savchuk cbca0e9fa9 update libraries 2018-06-14 11:43:14 +03:00
Andrey Savchuk 1b92bd9d7d add valid local config 2018-05-03 18:59:21 +03:00
andrey.savchuk be84492c3d change auth method to outer 2018-05-01 00:09:17 +03:00
andrey.savchuk 00f555442d update lib 2018-04-30 23:57:10 +03:00
andrey.savchuk dc572d0f65 add token index 2018-04-30 23:35:43 +03:00
andrey.savchuk 256dc78e5b entities into lib 2018-04-30 23:27:09 +03:00
andrey.savchuk b6e13fb4af update lib db 2018-04-30 23:05:04 +03:00
andrey.savchuk 1109b9f12e to channel 2018-04-30 22:49:37 +03:00
andrey.savchuk 0bdedc65ad fix initialize db connection 2018-04-30 19:43:38 +03:00
andrey.savchuk 7ffe48855f add announcing convert addresses and receiving router address 2018-04-30 17:14:47 +03:00
Andrey Savchuk 266a5cb5d8 change grpc outer address 2018-04-27 20:18:52 +03:00
Andrey Savchuk 678147c9ed add crud for users 2018-04-27 20:18:12 +03:00
andrey.savchuk 4e608d872a inw 2018-04-27 02:32:52 +03:00
723 changed files with 54113 additions and 17946 deletions

No files matched your search

+9
View File
@@ -20,7 +20,12 @@ linters:
- wsl_v5 # расставление пробелов очень индивидуально
- godoclint # ругается на // nolint, не удобно
- prealloc # слишком аггресивный, в большинстве случаев не требуется
- gomodguard # deprecated
- goconst # слишком агрессивный
settings:
exhaustruct_v5:
allow-empty: true
explicit-mode: true
cyclop:
max-complexity: 15 # по умолчанию 10 мало
funlen:
@@ -60,6 +65,9 @@ linters:
- unqueryvet
- prealloc
path: ".*_test\\.go$"
- linters:
- goconst
path: "tests/" # компонентные тесты: фикстуры и моки не выносим в константы
paths:
- third_party$
- builtin$
@@ -73,3 +81,4 @@ formatters:
- third_party$
- builtin$
- examples$
+1 -1
View File
@@ -1 +1 @@
7.1.0
7.2.0
+5
View File
@@ -1,3 +1,8 @@
### v7.2.0
* Добавлено поле `application_group` в таблицу `roles`
* Добавлен для запросов `admin/role/create` и `admin/role/update`, необязателен
* Изменен эндпоинт `admin/role/all`, теперь результаты фильтруются по группе из тела запроса, при пустом теле без фильтрации
* Добавлена возможность скачивания и формирования CSV
### v7.1.0
* переименование авторизации через SUDIR в OAuth:
* Эндпоинты: `admin/auth/login_with_oauth`, `admin/ui_settings/oauth`
+5 -5
View File
@@ -16,7 +16,7 @@ import (
"github.com/txix-open/isp-kit/dbrx"
"github.com/txix-open/isp-kit/dbx"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc"
"github.com/txix-open/isp-kit/http"
"github.com/txix-open/isp-kit/http/httpcli"
"github.com/txix-open/isp-kit/http/httpclix"
"github.com/txix-open/isp-kit/log"
@@ -26,7 +26,7 @@ import (
type Assembly struct {
boot *bootstrap.Bootstrap
db *dbrx.Client
server *grpc.Server
server *http.Server
oauthCli *httpcli.Client
logger *log.Adapter
bgjobCli *bgjobx.Client
@@ -43,7 +43,7 @@ func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
return &Assembly{
boot: boot,
db: db,
server: grpc.NewServer(),
server: http.NewServer(logger),
logger: logger,
oauthCli: httpclix.Default(httpcli.WithMiddlewares(httpclix.Log(wrappedLogger))),
bgjobCli: bgjobCli,
@@ -109,7 +109,7 @@ func (a *Assembly) Runners() []app.Runner {
app.RunnerFunc(func(ctx context.Context) error {
err := a.server.ListenAndServe(a.boot.BindingAddress)
if err != nil {
return errors.WithMessage(err, "listen ans serve grpc server")
return errors.WithMessage(err, "listen and serve http server")
}
return nil
}),
@@ -127,7 +127,7 @@ func (a *Assembly) Closers() []app.Closer {
return []app.Closer{
a.boot.ClusterCli,
app.CloserFunc(func() error {
a.server.Shutdown()
_ = a.server.Shutdown(context.Background())
return nil
}),
app.CloserFunc(func() error {
+17 -4
View File
@@ -18,9 +18,10 @@ import (
"github.com/txix-open/isp-kit/bgjobx"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc/endpoint"
"github.com/txix-open/isp-kit/grpc/isp"
"github.com/txix-open/isp-kit/http/endpoint"
"github.com/txix-open/isp-kit/http/endpoint/httplog"
"github.com/txix-open/isp-kit/http/httpcli"
"github.com/txix-open/isp-kit/http/router"
"github.com/txix-open/isp-kit/log"
)
@@ -44,7 +45,7 @@ func NewLocator(logger log.Logger, oauthCli *httpcli.Client, db DB) Locator {
}
type Config struct {
Handler isp.BackendServiceServer
Handler *router.Router
BgJobCfg []bgjobx.WorkerConfig
}
@@ -97,6 +98,14 @@ func (l Locator) Config(
uiSettingsService := service.NewUiSettings(oauthBaseUrl, oauthSettings)
downloadService := service.NewDownload(
auditService,
userService,
tokenService,
roleService,
permissionsService,
)
userController := controller.NewUser(userService)
customizationController := controller.NewCustomization(cfg.UiDesign)
authController := controller.NewAuth(authService, l.logger)
@@ -106,8 +115,11 @@ func (l Locator) Config(
roleController := controller.NewRole(roleService)
permissionController := controller.NewPermissions(permissionsService)
uiSettingsController := controller.NewUiSettings(uiSettingsService)
downloadController := controller.NewDownload(downloadService)
wrapper := endpoint.DefaultWrapper(l.logger, httplog.Log(l.logger, true))
handler := routes.Handler(
endpoint.DefaultWrapper(l.logger),
wrapper,
routes.Controllers{
User: userController,
Customization: customizationController,
@@ -118,6 +130,7 @@ func (l Locator) Config(
Role: roleController,
Permissions: permissionController,
UiSettings: uiSettingsController,
Download: downloadController,
},
)
+35
View File
@@ -0,0 +1,35 @@
package auth
import (
"net/http"
"strconv"
"github.com/txix-open/isp-kit/errors"
)
// StringFromHeader extracts a string value from header by key.
// Returns an error if header is nil or the key is not found.
func StringFromHeader(key string, h http.Header) (string, error) {
if h == nil {
return "", errors.New("header is nil")
}
values := h.Values(key)
if len(values) == 0 {
return "", errors.Errorf("'%s' is expected in header", key)
}
return values[0], nil
}
// IntFromHeader extracts an integer value from header by key.
// Returns an error if the key is not found or the value cannot be parsed as an integer.
func IntFromHeader(key string, h http.Header) (int, error) {
value, err := StringFromHeader(key, h)
if err != nil {
return 0, err
}
intValue, err := strconv.Atoi(value)
if err != nil {
return 0, errors.WithMessagef(err, "parse '%s' to int", key)
}
return intValue, nil
}
+36 -35
View File
@@ -2,12 +2,12 @@ package controller
import (
"context"
"net/http"
"isp-admin-service/domain"
"github.com/txix-open/isp-kit/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/txix-open/isp-kit/http/apierrors"
)
type AuditService interface {
@@ -27,16 +27,17 @@ func NewAudit(service AuditService) Audit {
}
// All
// @Tags log
// @Summary Получение списка логов
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.AuditPageRequest true "Тело запроса"
// @Success 200 {object} domain.AuditResponse
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
// @Failure 500 {object} domain.GrpcError
// @Router /log/all [POST]
//
// @Tags log
// @Summary Получение списка логов
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.AuditPageRequest true "Тело запроса (пагинация, сортировка, фильтры)"
// @Success 200 {object} domain.AuditResponse
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
// @Failure 500 {object} apierrors.Error
// @Router /log/all [POST]
func (c Audit) All(ctx context.Context, req domain.AuditPageRequest) (*domain.AuditResponse, error) {
if req.Order == nil {
req.Order = &domain.OrderParams{
@@ -49,38 +50,38 @@ func (c Audit) All(ctx context.Context, req domain.AuditPageRequest) (*domain.Au
}
// Events
// @Tags log
// @Summary Получение списка логов
// @Description Возвращает полный список доступных событий аудита
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.AuditResponse true "Тело запроса"
// @Success 200 {array} domain.AuditEvent
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
// @Failure 500 {object} domain.GrpcError
// @Router /log/events [POST]
//
// @Tags log
// @Summary Получение списка событий аудита
// @Description Возвращает полный список доступных событий аудита
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 {array} domain.AuditEvent
// @Failure 500 {object} apierrors.Error
// @Router /log/events [POST]
func (c Audit) Events(ctx context.Context) ([]domain.AuditEvent, error) {
return c.service.Events(ctx)
}
// SetEvents
// @Tags log
// @Summary Получение списка логов
// @Description Всегда возвращает полный список доступных событий аудита
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.SetAuditEvent true "Тело запроса"
// @Success 200
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
// @Failure 500 {object} domain.GrpcError
// @Router /log/set_events [POST]
//
// @Tags log
// @Summary Установить события аудита
// @Description Устанавливает (обновляет) набор активных событий аудита.
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body []domain.SetAuditEvent true "Список событий аудита для установки"
// @Success 200 {object} map[string]interface{} "События успешно установлены"
// @Failure 400 {object} apierrors.Error "Неизвестное событие аудита"
// @Failure 500 {object} apierrors.Error
// @Router /log/set_events [POST]
func (c Audit) SetEvents(ctx context.Context, req []domain.SetAuditEvent) error {
err := c.service.SetEvents(ctx, req)
switch {
case errors.As(err, &domain.UnknownAuditEventError{}):
return status.Error(codes.InvalidArgument, err.Error())
return apierrors.New(http.StatusBadRequest, domain.UnknownAuditEventErrorCode, err.Error(), err)
default:
return err
}
+64 -60
View File
@@ -2,16 +2,15 @@ package controller
import (
"context"
"net/http"
"strconv"
"isp-admin-service/auth"
"isp-admin-service/domain"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc"
"github.com/txix-open/isp-kit/http/apierrors"
"github.com/txix-open/isp-kit/log"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
type authService interface {
@@ -33,18 +32,19 @@ func NewAuth(authService authService, logger log.Logger) Auth {
}
// Logout
// @Tags auth
// @Summary Выход из авторизованной сессии
// @Description Выход из авторизованной сессии администрирования
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
// @Failure 500 {object} domain.GrpcError
// @Router /auth/logout [POST]
func (a Auth) Logout(ctx context.Context, authData grpc.AuthData) error {
adminId, err := getAdminId(authData)
//
// @Tags auth
// @Summary Выход из авторизованной сессии
// @Description Выход из авторизованной сессии администрирования
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 {object} map[string]interface{} "Успешный выход"
// @Failure 400 {object} apierrors.Error "Невалидный токен"
// @Failure 500 {object} apierrors.Error
// @Router /auth/logout [POST]
func (a Auth) Logout(ctx context.Context, r *http.Request) error {
adminId, err := getAdminId(r)
if err != nil {
return err
}
@@ -58,19 +58,20 @@ func (a Auth) Logout(ctx context.Context, authData grpc.AuthData) error {
}
// LogoutWithReason
// @Tags auth
// @Summary Выход по бездействию из авторизованной сессии
// @Description Выход по бездействию из авторизованной сессии администрирования
// @Accept json
// @Produce json
// @Param body body domain.LogoutRequest true "Тело запроса"
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
// @Failure 500 {object} domain.GrpcError
// @Router /auth/logout_with_reason [POST]
func (a Auth) LogoutWithReason(ctx context.Context, authData grpc.AuthData, logoutRequest domain.LogoutRequest) error {
adminId, err := getAdminId(authData)
//
// @Tags auth
// @Summary Выход по бездействию из авторизованной сессии
// @Description Выход по бездействию из авторизованной сессии администрирования
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.LogoutRequest true "Тело запроса"
// @Success 200 {object} map[string]interface{} "Успешный выход"
// @Failure 400 {object} apierrors.Error "Невалидный токен"
// @Failure 500 {object} apierrors.Error
// @Router /auth/logout_with_reason [POST]
func (a Auth) LogoutWithReason(ctx context.Context, logoutRequest domain.LogoutRequest, r *http.Request) error {
adminId, err := getAdminId(r)
if err != nil {
return err
}
@@ -84,28 +85,30 @@ func (a Auth) LogoutWithReason(ctx context.Context, authData grpc.AuthData, logo
}
// Login
// @Tags auth
// @Summary Авторизация по логину и паролю
// @Description Авторизация с получением токена администратора
// @Accept json
// @Produce json
// @Param body body domain.LoginRequest true "Тело запроса"
// @Success 200 {object} domain.LoginResponse
// @Failure 400 {object} domain.GrpcError
// @Failure 401 {object} domain.GrpcError "Данные для авторизации не верны"
// @Failure 500 {object} domain.GrpcError
// @Router /auth/login [POST]
//
// @Tags auth
// @Summary Авторизация по логину и паролю
// @Description Авторизация с получением токена администратора
// @Accept json
// @Produce json
// @Param body body domain.LoginRequest true "Тело запроса"
// @Success 200 {object} domain.LoginResponse
// @Failure 400 {object} apierrors.Error
// @Failure 401 {object} apierrors.Error "Данные для авторизации не верны"
// @Failure 429 {object} apierrors.Error "Слишком много запросов на авторизацию"
// @Failure 500 {object} apierrors.Error
// @Router /auth/login [POST]
func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*domain.LoginResponse, error) {
auth, err := a.authService.Login(ctx, authRequest)
switch {
case errors.Is(err, domain.ErrOauthAuthorization):
return nil, status.Error(codes.InvalidArgument, "plain auth is not available")
return nil, apierrors.New(http.StatusBadRequest, domain.ErrOauthAuthorizationCode, err.Error(), err)
case errors.Is(err, domain.ErrUnauthenticated):
a.logger.Error(ctx, err.Error())
return nil, status.Error(codes.Unauthenticated, "invalid credential")
return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnauthenticatedCode, err.Error(), err)
case errors.Is(err, domain.ErrTooManyLoginRequests):
return nil, status.Error(codes.ResourceExhausted, "too many requests")
return nil, apierrors.New(http.StatusTooManyRequests, domain.ErrTooManyLoginRequestsCode, err.Error(), err)
case err != nil:
return nil, errors.WithMessage(err, "login")
default:
@@ -114,25 +117,26 @@ func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*doma
}
// LoginWithOauth
// @Tags auth
// @Summary Авторизация по авторизационному коду от OAuth
// @Description Авторизация с получением токена администратора
// @Accept json
// @Produce json
// @Param body body domain.LoginOauthRequest true "Тело запроса"
// @Success 200 {object} domain.LoginResponse
// @Failure 401 {object} domain.GrpcError "Некорректный код для авторизации или неизвестное название клиента"
// @Failure 412 {object} domain.GrpcError "Авторизация OAuth не настроена на сервере"
// @Failure 500 {object} domain.GrpcError
// @Router /auth/login_with_oauth [POST]
//
// @Tags auth
// @Summary Авторизация по авторизационному коду от OAuth
// @Description Авторизация с получением токена администратора.
// @Accept json
// @Produce json
// @Param body body domain.LoginOauthRequest true "Тело запроса"
// @Success 200 {object} domain.LoginResponse
// @Failure 400 {object} apierrors.Error "Авторизация OAuth не настроена на сервере"
// @Failure 401 {object} apierrors.Error "Некорректный код для авторизации или неизвестное название клиента"
// @Failure 500 {object} apierrors.Error
// @Router /auth/login_with_oauth [POST]
func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthRequest) (*domain.LoginResponse, error) {
auth, err := a.authService.LoginWithOauth(ctx, request)
switch {
case errors.Is(err, domain.ErrOauthIsMissed):
return nil, status.Error(codes.FailedPrecondition, "oauth is not configured")
return nil, apierrors.New(http.StatusBadRequest, domain.ErrOauthIsMissedCode, err.Error(), err)
case errors.Is(err, domain.ErrUnauthenticated):
return nil, status.Error(codes.Unauthenticated, "invalid code")
return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnauthenticatedCode, err.Error(), err)
case err != nil:
return nil, errors.WithMessage(err, "login with oauth")
default:
@@ -140,15 +144,15 @@ func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthReque
}
}
func getAdminId(authData grpc.AuthData) (int64, error) {
token, err := grpc.StringFromMd(domain.AdminAuthIdHeader, metadata.MD(authData))
func getAdminId(r *http.Request) (int64, error) {
token, err := auth.StringFromHeader(domain.AdminAuthIdHeader, r.Header)
if err != nil {
return 0, status.Error(codes.InvalidArgument, err.Error())
return 0, apierrors.NewBusinessError(http.StatusBadRequest, err.Error(), err)
}
adminId, err := strconv.Atoi(token)
if err != nil {
return 0, status.Error(codes.InvalidArgument, "admin id is not a number")
return 0, apierrors.NewBusinessError(http.StatusBadRequest, err.Error(), err)
}
return int64(adminId), nil
+11 -10
View File
@@ -19,16 +19,17 @@ func NewCustomization(uiCfg conf.UIDesign) Customization {
}
// GetUIDesign
// @Tags user
// @Summary Получение внешнего вида
// @Description Получение внешнего вида (палитра и наименование) админ-интерфейса
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 {object} domain.UIDesign
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
// @Failure 500 {object} domain.GrpcError
// @Router /user/get_design [POST]
//
// @Tags user
// @Summary Получение внешнего вида
// @Description Получение внешнего вида (палитра и наименование) админ-интерфейса
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 {object} domain.UIDesign
// @Failure 400 {object} apierrors.Error "Невалидный токен"
// @Failure 500 {object} apierrors.Error
// @Router /user/get_design [POST]
func (c Customization) GetUIDesign() (domain.UIDesign, error) {
return c.uiCfg, nil
}
+102
View File
@@ -0,0 +1,102 @@
package controller
import (
"context"
"net/http"
"isp-admin-service/domain"
"github.com/txix-open/isp-kit/errors"
)
type DownloadService interface {
DownloadUsers(ctx context.Context, req domain.UsersPageRequest, w http.ResponseWriter) error
DownloadSessions(ctx context.Context, req domain.SessionPageRequest, w http.ResponseWriter) error
DownloadAudit(ctx context.Context, req domain.AuditPageRequest, w http.ResponseWriter) error
DownloadRoles(ctx context.Context, w http.ResponseWriter) error
}
type Download struct {
service DownloadService
}
func NewDownload(service DownloadService) Download {
return Download{
service: service,
}
}
// Users
//
// @Tags Download
// @Summary Скачать список пользователей в csv
// @Accept json
// @Produce text/csv
// @Param body body domain.UsersPageRequest true "Тело запроса"
// @Success 200
// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```"
// @Router /user/download [POST]
func (c Download) Users(ctx context.Context, req domain.UsersPageRequest, w http.ResponseWriter) error {
err := c.service.DownloadUsers(ctx, req, w)
if err != nil {
return errors.WithMessage(err, "download users")
}
return nil
}
// Sessions
//
// @Tags Download
// @Summary Скачать список сессий в csv
// @Accept json
// @Produce text/csv
// @Param body body domain.SessionPageRequest true "Тело запроса"
// @Success 200
// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```"
// @Router /session/download [POST]
func (c Download) Sessions(ctx context.Context, req domain.SessionPageRequest, w http.ResponseWriter) error {
err := c.service.DownloadSessions(ctx, req, w)
if err != nil {
return errors.WithMessage(err, "download sessions")
}
return nil
}
// Audit
//
// @Tags Download
// @Summary Скачать журнал аудита в csv
// @Accept json
// @Produce text/csv
// @Param body body domain.AuditPageRequest true "Тело запроса"
// @Success 200
// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```"
// @Router /log/download [POST]
func (c Download) Audit(ctx context.Context, req domain.AuditPageRequest, w http.ResponseWriter) error {
err := c.service.DownloadAudit(ctx, req, w)
if err != nil {
return errors.WithMessage(err, "download audit")
}
return nil
}
// Roles
//
// @Tags Download
// @Summary Скачать матрицу ролей в csv
// @Accept json
// @Produce text/csv
// @Success 200
// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```"
// @Router /role/download [POST]
func (c Download) Roles(ctx context.Context, w http.ResponseWriter) error {
err := c.service.DownloadRoles(ctx, w)
if err != nil {
return errors.WithMessage(err, "download roles")
}
return nil
}
+9 -7
View File
@@ -21,13 +21,15 @@ func NewPermissions(permissionsService permissionsService) Permissions {
}
// GetPermissions
// @Tags user
// @Summary Получить все разрашения
// @Description Получить все разрашения
// @Accept json
// @Produce json
// @Success 200 {array} domain.Permission
// @Router /user/get_permissions [POST]
//
// @Tags user
// @Summary Получить все разрешения
// @Description Получить все разрешения
// @Accept json
// @Produce json
// @Success 200 {array} domain.Permission
// @Failure 500 {object} apierrors.Error
// @Router /user/get_permissions [POST]
func (u Permissions) GetPermissions(ctx context.Context) []domain.Permission {
return u.permissionsService.All(ctx)
}
+63 -60
View File
@@ -2,17 +2,16 @@ package controller
import (
"context"
"net/http"
"isp-admin-service/domain"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/txix-open/isp-kit/http/apierrors"
)
type roleService interface {
All(ctx context.Context) ([]domain.Role, error)
All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error)
Create(ctx context.Context, req domain.CreateRoleRequest, adminId int64) (*domain.Role, error)
Update(ctx context.Context, req domain.UpdateRoleRequest, adminId int64) (*domain.Role, error)
Delete(ctx context.Context, req domain.DeleteRoleRequest, adminId int64) error
@@ -29,18 +28,19 @@ func NewRole(roleService roleService) Role {
}
// All
// @Tags role
// @Summary Список ролей
// @Description Получить список ролей
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 {array} domain.Role
// @Failure 400 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /role/all [POST]
func (u Role) All(ctx context.Context) ([]domain.Role, error) {
users, err := u.roleService.All(ctx)
//
// @Tags role
// @Summary Список ролей
// @Description Получить список ролей
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 {array} domain.Role
// @Failure 400 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /role/all [POST]
func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error) {
users, err := u.roleService.All(ctx, req)
if err != nil {
return nil, errors.WithMessage(err, "get roles")
}
@@ -49,20 +49,21 @@ func (u Role) All(ctx context.Context) ([]domain.Role, error) {
}
// CreateRole
// @Tags user
// @Summary Создать роль
// @Description Создать роль
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.CreateRoleRequest true "Тело запроса"
// @Success 200 {object} domain.User
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
// @Failure 409 {object} domain.GrpcError "Роль с указанным именем уже существует"
// @Failure 500 {object} domain.GrpcError
// @Router /role/create [POST]
func (u Role) CreateRole(ctx context.Context, authData grpc.AuthData, req domain.CreateRoleRequest) (*domain.Role, error) {
adminId, err := getAdminId(authData)
//
// @Tags role
// @Summary Создать роль
// @Description Создать роль
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.CreateRoleRequest true "Тело запроса"
// @Success 200 {object} domain.Role
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
// @Failure 409 {object} apierrors.Error "Роль с указанным именем уже существует"
// @Failure 500 {object} apierrors.Error
// @Router /role/create [POST]
func (u Role) CreateRole(ctx context.Context, req domain.CreateRoleRequest, r *http.Request) (*domain.Role, error) {
adminId, err := getAdminId(r)
if err != nil {
return nil, err
}
@@ -70,7 +71,7 @@ func (u Role) CreateRole(ctx context.Context, authData grpc.AuthData, req domain
role, err := u.roleService.Create(ctx, req, adminId)
switch {
case errors.Is(err, domain.ErrAlreadyExists):
return nil, status.Error(codes.AlreadyExists, "role with current name already exists")
return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
case err != nil:
return nil, errors.WithMessage(err, "create role")
default:
@@ -79,20 +80,21 @@ func (u Role) CreateRole(ctx context.Context, authData grpc.AuthData, req domain
}
// UpdateRole
// @Tags role
// @Summary Обновить роль
// @Description Обновить данные существующую роль
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.UpdateRoleRequest true "Тело запроса"
// @Success 200 {object} domain.Role
// @Failure 404 {object} domain.GrpcError "Роль с указанным id не существует"
// @Failure 409 {object} domain.GrpcError "Роль с указанным именем уже существует"
// @Failure 500 {object} domain.GrpcError
// @Router /role/update [POST]
func (u Role) UpdateRole(ctx context.Context, authData grpc.AuthData, req domain.UpdateRoleRequest) (*domain.Role, error) {
adminId, err := getAdminId(authData)
//
// @Tags role
// @Summary Обновить роль
// @Description Обновить данные существующую роль
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.UpdateRoleRequest true "Тело запроса"
// @Success 200 {object} domain.Role
// @Failure 404 {object} apierrors.Error "Роль с указанным id не существует"
// @Failure 409 {object} apierrors.Error "Роль с указанным именем уже существует"
// @Failure 500 {object} apierrors.Error
// @Router /role/update [POST]
func (u Role) UpdateRole(ctx context.Context, req domain.UpdateRoleRequest, r *http.Request) (*domain.Role, error) {
adminId, err := getAdminId(r)
if err != nil {
return nil, err
}
@@ -100,9 +102,9 @@ func (u Role) UpdateRole(ctx context.Context, authData grpc.AuthData, req domain
result, err := u.roleService.Update(ctx, req, adminId)
switch {
case errors.Is(err, domain.ErrNotFound):
return nil, status.Error(codes.NotFound, "role not found")
return nil, apierrors.New(http.StatusNotFound, domain.ErrNotFoundCode, err.Error(), err)
case errors.Is(err, domain.ErrAlreadyExists):
return nil, status.Error(codes.AlreadyExists, "role with current name already exists")
return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
case err != nil:
return nil, errors.WithMessage(err, "update role")
default:
@@ -111,19 +113,20 @@ func (u Role) UpdateRole(ctx context.Context, authData grpc.AuthData, req domain
}
// DeleteRole
// @Tags role
// @Summary Удалить роль
// @Description Удалить существующую роль
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.DeleteRoleRequest true "Тело запроса"
// @Success 200
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
// @Failure 500 {object} domain.GrpcError
// @Router /role/delete [POST]
func (u Role) DeleteRole(ctx context.Context, authData grpc.AuthData, req domain.DeleteRoleRequest) error {
adminId, err := getAdminId(authData)
//
// @Tags role
// @Summary Удалить роль
// @Description Удалить существующую роль
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.DeleteRoleRequest true "Тело запроса"
// @Success 200
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
// @Failure 500 {object} apierrors.Error
// @Router /role/delete [POST]
func (u Role) DeleteRole(ctx context.Context, req domain.DeleteRoleRequest, r *http.Request) error {
adminId, err := getAdminId(r)
if err != nil {
return err
}
+21 -19
View File
@@ -6,7 +6,7 @@ import (
"isp-admin-service/domain"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc/apierrors"
"github.com/txix-open/isp-kit/http/apierrors"
)
type SecureService interface {
@@ -25,15 +25,16 @@ func NewSecure(service SecureService) Secure {
}
// Authenticate
// @Tags secure
// @Summary Метод аутентификации токена
// @Description Проверяет токен и возвращает идентификатор администратора
// @Accept json
// @Produce json
// @Param body body domain.SecureAuthRequest true "Тело запроса"
// @Success 200 {object} domain.SecureAuthResponse
// @Failure 500 {object} domain.GrpcError
// @Router /secure/authenticate [POST]
//
// @Tags secure
// @Summary Метод аутентификации токена
// @Description Проверяет токен и возвращает идентификатор администратора
// @Accept json
// @Produce json
// @Param body body domain.SecureAuthRequest true "Тело запроса"
// @Success 200 {object} domain.SecureAuthResponse
// @Failure 500 {object} apierrors.Error
// @Router /secure/authenticate [POST]
func (s Secure) Authenticate(ctx context.Context, req domain.SecureAuthRequest) (*domain.SecureAuthResponse, error) {
adminId, err := s.service.Authenticate(ctx, req.Token)
switch {
@@ -61,15 +62,16 @@ func (s Secure) Authenticate(ctx context.Context, req domain.SecureAuthRequest)
}
// Authorize
// @Tags secure
// @Summary Метод авторизации для администратора
// @Description Проверяет наличие у администратора необходимого разрешения
// @Accept json
// @Produce json
// @Param body body domain.SecureAuthzRequest true "Тело запроса"
// @Success 200 {object} domain.SecureAuthzResponse
// @Failure 500 {object} domain.GrpcError
// @Router /secure/authorize [POST]
//
// @Tags secure
// @Summary Метод авторизации для администратора
// @Description Проверяет наличие у администратора необходимого разрешения
// @Accept json
// @Produce json
// @Param body body domain.SecureAuthzRequest true "Тело запроса"
// @Success 200 {object} domain.SecureAuthzResponse
// @Failure 500 {object} apierrors.Error
// @Router /secure/authorize [POST]
func (s Secure) Authorize(ctx context.Context, req domain.SecureAuthzRequest) (*domain.SecureAuthzResponse, error) {
ok, err := s.service.Authorize(ctx, req.AdminId, req.Permission)
if err != nil {
+22 -20
View File
@@ -22,16 +22,17 @@ func NewSession(service SessionService) Session {
}
// All
// @Tags session
// @Summary Получение списка сессий
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.SessionPageRequest true "Тело запроса"
// @Success 200 {object} domain.SessionResponse
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
// @Failure 500 {object} domain.GrpcError
// @Router /session/all [POST]
//
// @Tags session
// @Summary Получение списка сессий
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.SessionPageRequest true "Тело запроса"
// @Success 200 {object} domain.SessionResponse
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
// @Failure 500 {object} apierrors.Error
// @Router /session/all [POST]
func (c Session) All(ctx context.Context, req domain.SessionPageRequest) (*domain.SessionResponse, error) {
if req.Order == nil {
req.Order = &domain.OrderParams{
@@ -44,16 +45,17 @@ func (c Session) All(ctx context.Context, req domain.SessionPageRequest) (*domai
}
// Revoke
// @Tags session
// @Summary Отзыв сессии
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.RevokeRequest true "Тело запроса"
// @Success 200
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
// @Failure 500 {object} domain.GrpcError
// @Router /session/revoke [POST]
//
// @Tags session
// @Summary Отзыв сессии
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.RevokeRequest true "Тело запроса"
// @Success 200
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
// @Failure 500 {object} apierrors.Error
// @Router /session/revoke [POST]
func (c Session) Revoke(ctx context.Context, req domain.RevokeRequest) error {
return c.service.Revoke(ctx, req.Id)
}
+15 -14
View File
@@ -3,10 +3,10 @@ package controller
import (
"context"
"isp-admin-service/domain"
"net/http"
"github.com/txix-open/isp-kit/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/txix-open/isp-kit/http/apierrors"
)
type UiSettingsService interface {
@@ -24,22 +24,23 @@ func NewUiSettings(service UiSettingsService) UiSettings {
}
// UiOauthSettings
// @Tags ui_settings
// @Summary Получение настроек для ui для авторизации через OAuth
// @Description Получение настроек для ui для авторизации через OAuth
// @Accept json
// @Produce json
// @Param body body domain.ClientNameRequest true "Тело запроса"
// @Success 200 {object} domain.UiOauthSetting
// @Failure 400 {object} domain.GrpcError
// @Failure 401 {object} domain.GrpcError "Неизвестное название клиента"
// @Failure 500 {object} domain.GrpcError
// @Router /ui_settings/oauth [POST]
//
// @Tags ui_settings
// @Summary Получение настроек для ui для авторизации через OAuth
// @Description Получение настроек для ui для авторизации через OAuth
// @Accept json
// @Produce json
// @Param body body domain.ClientNameRequest true "Тело запроса"
// @Success 200 {object} domain.UiOauthSetting
// @Failure 400 {object} apierrors.Error
// @Failure 401 {object} apierrors.Error "Неизвестное название клиента"
// @Failure 500 {object} apierrors.Error
// @Router /ui_settings/oauth [POST]
func (c UiSettings) OauthSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiOauthSetting, error) {
resp, err := c.service.OauthSettings(ctx, req)
switch {
case errors.Is(err, domain.ErrUnknownClient):
return nil, status.Error(codes.Unauthenticated, "invalid client name")
return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnknownClientCode, err.Error(), err)
case err != nil:
return nil, err
default:
+127 -120
View File
@@ -2,15 +2,13 @@ package controller
import (
"context"
"net/http"
"github.com/txix-open/isp-kit/grpc/apierrors"
"github.com/txix-open/isp-kit/http/apierrors"
"isp-admin-service/domain"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type userService interface {
@@ -36,19 +34,20 @@ func NewUser(userService userService) User {
}
// GetProfile
// @Tags user
// @Summary Получить профиль
// @Description Получить данные профиля
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 {object} domain.AdminUserShort
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
// @Failure 404 {object} domain.GrpcError "Пользователя не существует"
// @Failure 500 {object} domain.GrpcError
// @Router /user/get_profile [POST]
func (u User) GetProfile(ctx context.Context, authData grpc.AuthData) (*domain.AdminUserShort, error) {
adminId, err := getAdminId(authData)
//
// @Tags user
// @Summary Получить профиль
// @Description Получить данные профиля
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 {object} domain.AdminUserShort
// @Failure 401 {object} apierrors.Error "Невалидный токен"
// @Failure 404 {object} apierrors.Error "Пользователя не существует"
// @Failure 500 {object} apierrors.Error
// @Router /user/get_profile [POST]
func (u User) GetProfile(ctx context.Context, r *http.Request) (*domain.AdminUserShort, error) {
adminId, err := getAdminId(r)
if err != nil {
return nil, err
}
@@ -56,9 +55,9 @@ func (u User) GetProfile(ctx context.Context, authData grpc.AuthData) (*domain.A
profile, err := u.userService.GetProfileById(ctx, adminId)
switch {
case errors.Is(err, domain.ErrUnauthenticated):
return nil, status.Error(codes.Unauthenticated, "user is blocked")
return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnauthenticatedCode, err.Error(), err)
case errors.Is(err, domain.ErrNotFound):
return nil, status.Error(codes.NotFound, "user not found")
return nil, apierrors.New(http.StatusNotFound, domain.ErrNotFoundCode, err.Error(), err)
case err != nil:
return nil, errors.WithMessage(err, "get profile")
default:
@@ -67,17 +66,18 @@ func (u User) GetProfile(ctx context.Context, authData grpc.AuthData) (*domain.A
}
// GetUsers
// @Tags user
// @Summary Список пользователей
// @Description Получить список пользователей
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.UsersPageRequest true "Тело запроса"
// @Success 200 {object} domain.UsersResponse
// @Failure 400 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /user/get_users [POST]
//
// @Tags user
// @Summary Список пользователей
// @Description Получить список пользователей
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.UsersPageRequest true "Тело запроса"
// @Success 200 {object} domain.UsersResponse
// @Failure 400 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /user/get_users [POST]
func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) (*domain.UsersResponse, error) {
if req.Order == nil {
req.Order = &domain.OrderParams{
@@ -95,16 +95,17 @@ func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) (*domai
}
// GetAllUsers
// @Tags user
// @Summary Список пользователей
// @Description Получить список пользователей
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 {object} domain.UsersResponse
// @Failure 400 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /user/get_all_users [POST]
//
// @Tags user
// @Summary Список пользователей
// @Description Получить список пользователей
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 {object} domain.UsersResponse
// @Failure 400 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /user/get_all_users [POST]
func (u User) GetAllUsers(ctx context.Context) (*domain.UsersResponse, error) {
users, err := u.userService.GetAllUsers(ctx)
if err != nil {
@@ -115,20 +116,21 @@ func (u User) GetAllUsers(ctx context.Context) (*domain.UsersResponse, error) {
}
// CreateUser
// @Tags user
// @Summary Создать пользователя
// @Description Создать пользователя
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.CreateUserRequest true "Тело запроса"
// @Success 200 {object} domain.User
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
// @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует"
// @Failure 500 {object} domain.GrpcError
// @Router /user/create_user [POST]
func (u User) CreateUser(ctx context.Context, authData grpc.AuthData, req domain.CreateUserRequest) (*domain.User, error) {
adminId, err := getAdminId(authData)
//
// @Tags user
// @Summary Создать пользователя
// @Description Создать пользователя
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.CreateUserRequest true "Тело запроса"
// @Success 200 {object} domain.User
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
// @Failure 409 {object} apierrors.Error "Пользователь с указанным email уже существует"
// @Failure 500 {object} apierrors.Error
// @Router /user/create_user [POST]
func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, r *http.Request) (*domain.User, error) {
adminId, err := getAdminId(r)
if err != nil {
return nil, err
}
@@ -136,7 +138,7 @@ func (u User) CreateUser(ctx context.Context, authData grpc.AuthData, req domain
user, err := u.userService.CreateUser(ctx, req, adminId)
switch {
case errors.Is(err, domain.ErrAlreadyExists):
return nil, status.Error(codes.AlreadyExists, "user with the same email already exists")
return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
case err != nil:
return nil, errors.WithMessage(err, "create user")
default:
@@ -145,21 +147,22 @@ func (u User) CreateUser(ctx context.Context, authData grpc.AuthData, req domain
}
// UpdateUser
// @Tags user
// @Summary Обновить пользователя
// @Description Обновить данные существующего пользователя
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.UpdateUserRequest true "Тело запроса"
// @Success 200 {object} domain.User
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
// @Failure 404 {object} domain.GrpcError "Пользователь с указанным id не существует"
// @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует"
// @Failure 500 {object} domain.GrpcError
// @Router /user/update_user [POST]
func (u User) UpdateUser(ctx context.Context, authData grpc.AuthData, req domain.UpdateUserRequest) (*domain.User, error) {
adminId, err := getAdminId(authData)
//
// @Tags user
// @Summary Обновить пользователя
// @Description Обновить данные существующего пользователя
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.UpdateUserRequest true "Тело запроса"
// @Success 200 {object} domain.User
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
// @Failure 404 {object} apierrors.Error "Пользователь с указанным id не существует"
// @Failure 409 {object} apierrors.Error "Пользователь с указанным email уже существует"
// @Failure 500 {object} apierrors.Error
// @Router /user/update_user [POST]
func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, r *http.Request) (*domain.User, error) {
adminId, err := getAdminId(r)
if err != nil {
return nil, err
}
@@ -167,11 +170,11 @@ func (u User) UpdateUser(ctx context.Context, authData grpc.AuthData, req domain
result, err := u.userService.UpdateUser(ctx, req, adminId)
switch {
case errors.Is(err, domain.ErrNotFound):
return nil, status.Error(codes.NotFound, "user not found")
return nil, apierrors.New(http.StatusNotFound, domain.ErrNotFoundCode, err.Error(), err)
case errors.Is(err, domain.ErrInvalid):
return nil, status.Error(codes.InvalidArgument, "user modification is not available")
return nil, apierrors.New(http.StatusBadRequest, domain.ErrInvalidCode, err.Error(), err)
case errors.Is(err, domain.ErrAlreadyExists):
return nil, status.Error(codes.AlreadyExists, "user with the same email already exists")
return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
case err != nil:
return nil, errors.WithMessage(err, "update user")
default:
@@ -180,19 +183,20 @@ func (u User) UpdateUser(ctx context.Context, authData grpc.AuthData, req domain
}
// DeleteUser
// @Tags user
// @Summary Удалить пользователя
// @Description Удалить существующего пользователя
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.IdentitiesRequest true "Тело запроса"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
// @Failure 500 {object} domain.GrpcError
// @Router /user/delete_user [POST]
func (u User) DeleteUser(ctx context.Context, authData grpc.AuthData, identities domain.IdentitiesRequest) (*domain.DeleteResponse, error) {
adminId, err := getAdminId(authData)
//
// @Tags user
// @Summary Удалить пользователя
// @Description Удалить существующего пользователя
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.IdentitiesRequest true "Тело запроса"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
// @Failure 500 {object} apierrors.Error
// @Router /user/delete_user [POST]
func (u User) DeleteUser(ctx context.Context, identities domain.IdentitiesRequest, r *http.Request) (*domain.DeleteResponse, error) {
adminId, err := getAdminId(r)
if err != nil {
return nil, err
}
@@ -206,18 +210,19 @@ func (u User) DeleteUser(ctx context.Context, authData grpc.AuthData, identities
}
// Block
// @Tags user
// @Summary Метод блокировки/разблокировки пользователя
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.IdRequest true "Тело запроса"
// @Success 200
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
// @Failure 500 {object} domain.GrpcError
// @Router /user/block_user [POST]
func (u User) Block(ctx context.Context, authData grpc.AuthData, identities domain.IdRequest) error {
adminId, err := getAdminId(authData)
//
// @Tags user
// @Summary Метод блокировки/разблокировки пользователя
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.IdRequest true "Тело запроса"
// @Success 200
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
// @Failure 500 {object} apierrors.Error
// @Router /user/block_user [POST]
func (u User) Block(ctx context.Context, identities domain.IdRequest, r *http.Request) error {
adminId, err := getAdminId(r)
if err != nil {
return err
}
@@ -230,32 +235,34 @@ func (u User) Block(ctx context.Context, authData grpc.AuthData, identities doma
}
// GetById
// @Tags user
// @Summary Метод получения данных по пользователю
// @Accept json
// @Produce json
// @Param body body domain.IdRequest true "Тело запроса"
// @Success 200 {object} domain.User
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
// @Failure 500 {object} domain.GrpcError
// @Router /user/get_by_id [POST]
//
// @Tags user
// @Summary Метод получения данных по пользователю
// @Accept json
// @Produce json
// @Param body body domain.IdRequest true "Тело запроса"
// @Success 200 {object} domain.User
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
// @Failure 500 {object} apierrors.Error
// @Router /user/get_by_id [POST]
func (u User) GetById(ctx context.Context, identities domain.IdRequest) (*domain.User, error) {
return u.userService.GetById(ctx, identities.UserId)
}
// ChangePassword
// @Tags user
// @Summary Метод изменения пароля пользователя
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.ChangePasswordRequest true "Тело запроса"
// @Success 200
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
// @Failure 500 {object} apierrors.Error "внутренняя ошибка"
// @Router /user/change_password [POST]
func (u User) ChangePassword(ctx context.Context, authData grpc.AuthData, req domain.ChangePasswordRequest) error {
adminId, err := getAdminId(authData)
//
// @Tags user
// @Summary Метод изменения пароля пользователя
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.ChangePasswordRequest true "Тело запроса"
// @Success 200
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса или неверный старый пароль"
// @Failure 500 {object} apierrors.Error "Внутренняя ошибка"
// @Router /user/change_password [POST]
func (u User) ChangePassword(ctx context.Context, req domain.ChangePasswordRequest, r *http.Request) error {
adminId, err := getAdminId(r)
if err != nil {
return err
}
@@ -263,7 +270,7 @@ func (u User) ChangePassword(ctx context.Context, authData grpc.AuthData, req do
err = u.userService.ChangePassword(ctx, adminId, req.OldPassword, req.NewPassword)
switch {
case errors.Is(err, domain.ErrInvalidPassword):
return apierrors.NewBusinessError(domain.ErrCodeInvalidPassword, "invalid password", err)
return apierrors.New(http.StatusBadRequest, domain.ErrCodeInvalidPassword, err.Error(), err)
case err != nil:
return apierrors.NewInternalServiceError(err)
default:
+258 -116
View File
@@ -46,19 +46,25 @@
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"401": {
"description": "Данные для авторизации не верны",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"429": {
"description": "Слишком много запросов на авторизацию",
"schema": {
"$ref": "#/definitions/apierrors.Error"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -66,7 +72,7 @@
},
"/auth/login_with_oauth": {
"post": {
"description": "Авторизация с получением токена администратора",
"description": "Авторизация с получением токена администратора.",
"consumes": [
"application/json"
],
@@ -95,22 +101,22 @@
"$ref": "#/definitions/domain.LoginResponse"
}
},
"400": {
"description": "Авторизация OAuth не настроена на сервере",
"schema": {
"$ref": "#/definitions/apierrors.Error"
}
},
"401": {
"description": "Некорректный код для авторизации или неизвестное название клиента",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
}
},
"412": {
"description": "Авторизация OAuth не настроена на сервере",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -140,18 +146,22 @@
],
"responses": {
"200": {
"description": "OK"
"description": "Успешный выход",
"schema": {
"type": "object",
"additionalProperties": true
}
},
"400": {
"description": "Невалидный токен",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -171,6 +181,13 @@
],
"summary": "Выход по бездействию из авторизованной сессии",
"parameters": [
{
"type": "string",
"description": "Токен администратора",
"name": "X-AUTH-ADMIN",
"in": "header",
"required": true
},
{
"description": "Тело запроса",
"name": "body",
@@ -179,29 +196,26 @@
"schema": {
"$ref": "#/definitions/domain.LogoutRequest"
}
},
{
"type": "string",
"description": "Токен администратора",
"name": "X-AUTH-ADMIN",
"in": "header",
"required": true
}
],
"responses": {
"200": {
"description": "OK"
"description": "Успешный выход",
"schema": {
"type": "object",
"additionalProperties": true
}
},
"400": {
"description": "Невалидный токен",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -228,7 +242,7 @@
"required": true
},
{
"description": "Тело запроса",
"description": "Тело запроса (пагинация, сортировка, фильтры)",
"name": "body",
"in": "body",
"required": true,
@@ -247,13 +261,49 @@
"400": {
"description": "Невалидное тело запроса",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
}
},
"/log/download": {
"post": {
"consumes": [
"application/json"
],
"produces": [
"text/csv"
],
"tags": [
"Download"
],
"summary": "Скачать журнал аудита в csv",
"parameters": [
{
"description": "Тело запроса",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/domain.AuditPageRequest"
}
}
],
"responses": {
"200": {
"description": "OK"
},
"500": {
"description": "Внутренняя ошибка сервиса ```{errorCode: -1}```",
"schema": {
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -271,7 +321,7 @@
"tags": [
"log"
],
"summary": "Получение списка логов",
"summary": "Получение списка событий аудита",
"parameters": [
{
"type": "string",
@@ -279,15 +329,6 @@
"name": "X-AUTH-ADMIN",
"in": "header",
"required": true
},
{
"description": "Тело запроса",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/domain.AuditResponse"
}
}
],
"responses": {
@@ -300,16 +341,10 @@
}
}
},
"400": {
"description": "Невалидное тело запроса",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -317,7 +352,7 @@
},
"/log/set_events": {
"post": {
"description": "Всегда возвращает полный список доступных событий аудита",
"description": "Устанавливает (обновляет) набор активных событий аудита.",
"consumes": [
"application/json"
],
@@ -327,7 +362,7 @@
"tags": [
"log"
],
"summary": "Получение списка логов",
"summary": "Установить события аудита",
"parameters": [
{
"type": "string",
@@ -337,29 +372,36 @@
"required": true
},
{
"description": "Тело запроса",
"description": "Список событий аудита для установки",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/domain.SetAuditEvent"
"type": "array",
"items": {
"$ref": "#/definitions/domain.SetAuditEvent"
}
}
}
],
"responses": {
"200": {
"description": "OK"
"description": "События успешно установлены",
"schema": {
"type": "object",
"additionalProperties": true
}
},
"400": {
"description": "Невалидное тело запроса",
"description": "Неизвестное событие аудита",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -400,13 +442,13 @@
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -422,7 +464,7 @@
"application/json"
],
"tags": [
"user"
"role"
],
"summary": "Создать роль",
"parameters": [
@@ -447,25 +489,25 @@
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/domain.User"
"$ref": "#/definitions/domain.Role"
}
},
"400": {
"description": "Невалидное тело запроса",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"409": {
"description": "Роль с указанным именем уже существует",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -509,13 +551,38 @@
"400": {
"description": "Невалидное тело запроса",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
}
},
"/role/download": {
"post": {
"consumes": [
"application/json"
],
"produces": [
"text/csv"
],
"tags": [
"Download"
],
"summary": "Скачать матрицу ролей в csv",
"responses": {
"200": {
"description": "OK"
},
"500": {
"description": "Внутренняя ошибка сервиса ```{errorCode: -1}```",
"schema": {
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -562,19 +629,19 @@
"404": {
"description": "Роль с указанным id не существует",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"409": {
"description": "Роль с указанным именем уже существует",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -614,7 +681,7 @@
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -654,7 +721,7 @@
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -700,13 +767,49 @@
"400": {
"description": "Невалидное тело запроса",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
}
},
"/session/download": {
"post": {
"consumes": [
"application/json"
],
"produces": [
"text/csv"
],
"tags": [
"Download"
],
"summary": "Скачать список сессий в csv",
"parameters": [
{
"description": "Тело запроса",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/domain.SessionPageRequest"
}
}
],
"responses": {
"200": {
"description": "OK"
},
"500": {
"description": "Внутренняя ошибка сервиса ```{errorCode: -1}```",
"schema": {
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -749,13 +852,13 @@
"400": {
"description": "Невалидное тело запроса",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -795,19 +898,19 @@
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"401": {
"description": "Неизвестное название клиента",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -850,13 +953,13 @@
"400": {
"description": "Невалидное тело запроса",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -897,13 +1000,13 @@
"description": "OK"
},
"400": {
"description": "Невалидное тело запроса",
"description": "Невалидное тело запроса или неверный старый пароль",
"schema": {
"$ref": "#/definitions/apierrors.Error"
}
},
"500": {
"description": "внутренняя ошибка",
"description": "Внутренняя ошибка",
"schema": {
"$ref": "#/definitions/apierrors.Error"
}
@@ -952,19 +1055,19 @@
"400": {
"description": "Невалидное тело запроса",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"409": {
"description": "Пользователь с указанным email уже существует",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -1011,13 +1114,49 @@
"400": {
"description": "Невалидное тело запроса",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
}
},
"/user/download": {
"post": {
"consumes": [
"application/json"
],
"produces": [
"text/csv"
],
"tags": [
"Download"
],
"summary": "Скачать список пользователей в csv",
"parameters": [
{
"description": "Тело запроса",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/domain.UsersPageRequest"
}
}
],
"responses": {
"200": {
"description": "OK"
},
"500": {
"description": "Внутренняя ошибка сервиса ```{errorCode: -1}```",
"schema": {
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -1055,13 +1194,13 @@
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -1100,13 +1239,13 @@
"400": {
"description": "Невалидное тело запроса",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -1144,13 +1283,13 @@
"400": {
"description": "Невалидный токен",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -1158,7 +1297,7 @@
},
"/user/get_permissions": {
"post": {
"description": "Получить все разрашения",
"description": "Получить все разрешения",
"consumes": [
"application/json"
],
@@ -1168,7 +1307,7 @@
"tags": [
"user"
],
"summary": "Получить все разрашения",
"summary": "Получить все разрешения",
"responses": {
"200": {
"description": "OK",
@@ -1178,6 +1317,12 @@
"$ref": "#/definitions/domain.Permission"
}
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/apierrors.Error"
}
}
}
}
@@ -1211,22 +1356,22 @@
"$ref": "#/definitions/domain.AdminUserShort"
}
},
"400": {
"401": {
"description": "Невалидный токен",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"404": {
"description": "Пользователя не существует",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -1273,13 +1418,13 @@
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -1326,25 +1471,25 @@
"400": {
"description": "Невалидное тело запроса",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"404": {
"description": "Пользователь с указанным id не существует",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"409": {
"description": "Пользователь с указанным email уже существует",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
"$ref": "#/definitions/apierrors.Error"
}
}
}
@@ -1564,6 +1709,10 @@
"domain.CreateRoleRequest": {
"type": "object",
"properties": {
"applicationGroup": {
"description": "Группа приложений",
"type": "string"
},
"changeMessage": {
"description": "Причина изменений",
"type": "string"
@@ -1656,21 +1805,6 @@
}
}
},
"domain.GrpcError": {
"type": "object",
"properties": {
"details": {
"type": "array",
"items": {}
},
"errorCode": {
"type": "string"
},
"errorMessage": {
"type": "string"
}
}
},
"domain.IdRequest": {
"type": "object",
"required": [
@@ -1805,6 +1939,10 @@
"domain.Role": {
"type": "object",
"properties": {
"applicationGroup": {
"description": "Группа приложений",
"type": "string"
},
"changeMessage": {
"description": "Причина изменений",
"type": "string"
@@ -2049,6 +2187,10 @@
"domain.UpdateRoleRequest": {
"type": "object",
"properties": {
"applicationGroup": {
"description": "Группа приложений",
"type": "string"
},
"changeMessage": {
"description": "Причина изменений",
"type": "string"
+1 -1
View File
@@ -17,7 +17,7 @@ type AuditResponse struct {
}
type AuditPageRequest struct {
LimitOffestParams
LimitOffsetParams
Order *OrderParams // Параметры сортировки
Query *AuditQuery // Параметры выборки
+13
View File
@@ -26,6 +26,19 @@ var (
ErrUnknownClient = errors.New("unknown client")
)
const (
UnknownAuditEventErrorCode = 601
ErrOauthAuthorizationCode = 602
ErrUnauthenticatedCode = 603
ErrTooManyLoginRequestsCode = 604
ErrOauthIsMissedCode = 605
ErrAlreadyExistsCode = 606
ErrNotFoundCode = 607
ErrUnknownClientCode = 608
ErrInvalidCode = 609
ErrInvalidPasswordCode = 610
)
type UnknownAuditEventError struct {
Event string
}
-7
View File
@@ -1,7 +0,0 @@
package domain
type GrpcError struct {
ErrorMessage string `json:"errorMessage"`
ErrorCode string `json:"errorCode"`
Details []any `json:"details"`
}
+1 -1
View File
@@ -7,7 +7,7 @@ const (
DefaultOrderType = "desc"
)
type LimitOffestParams struct {
type LimitOffsetParams struct {
Limit uint64 `validate:"required"` // Максимальное количество записей
Offset uint64 // Отступ для выборки
}
+25 -18
View File
@@ -5,32 +5,39 @@ import (
)
type Role struct {
Id int // Идентификатор роли
Name string // Название роли
ExternalGroup string // Внешнее название группы
ChangeMessage string // Причина изменений
Permissions []string // Набор прав
Immutable bool
Exclusive bool
CreatedAt time.Time // Дата создания
UpdatedAt time.Time // Дата обновления
Id int // Идентификатор роли
Name string // Название роли
ExternalGroup string // Внешнее название группы
ApplicationGroup string // Группа приложений
ChangeMessage string // Причина изменений
Permissions []string // Набор прав
Immutable bool
Exclusive bool
CreatedAt time.Time // Дата создания
UpdatedAt time.Time // Дата обновления
}
type CreateRoleRequest struct {
Name string // Название роли
ExternalGroup string // Внешнее название группы
ChangeMessage string // Причина изменений
Permissions []string // Набор прав
Name string // Название роли
ExternalGroup string // Внешнее название группы
ApplicationGroup string // Группа приложений
ChangeMessage string // Причина изменений
Permissions []string // Набор прав
}
type UpdateRoleRequest struct {
Id int // Идентификатор роли
Name string // Название роли
ExternalGroup string // Внешнее название группы
ChangeMessage string // Причина изменений
Permissions []string // Набор прав
Id int // Идентификатор роли
Name string // Название роли
ExternalGroup string // Внешнее название группы
ApplicationGroup string // Группа приложений
ChangeMessage string // Причина изменений
Permissions []string // Набор прав
}
type DeleteRoleRequest struct {
Id int // Идентификатор роли
}
type RoleAllRequest struct {
ApplicationGroup *string `validate:"omitnil,min=1"` // Фильтр по группе приложений
}
+24 -1
View File
@@ -4,6 +4,17 @@ import (
"time"
)
const (
SessionStatusAllowed = "ALLOWED"
SessionStatusAllowedRus = "Активная"
SessionStatusExpired = "EXPIRED"
SessionStatusExpiredRus = "Истекшая"
SessionStatusRevoked = "REVOKED"
SessionStatusRevokedRus = "Отмененная"
)
type Session struct {
Id int // Идентификатор сессии
UserId int // Идентификатор пользоватеккля
@@ -13,7 +24,7 @@ type Session struct {
}
type SessionPageRequest struct {
LimitOffestParams
LimitOffsetParams
Order *OrderParams // Параметры сортировки
Query *SessionQuery // Параметры выборки
@@ -35,3 +46,15 @@ type SessionResponse struct {
type RevokeRequest struct {
Id int `validate:"required"` // Идентификатор сессии
}
func (s Session) StatusRus() string {
switch s.Status {
case SessionStatusAllowed:
return SessionStatusAllowedRus
case SessionStatusExpired:
return SessionStatusExpiredRus
case SessionStatusRevoked:
return SessionStatusRevokedRus
}
return ""
}
+1 -1
View File
@@ -32,7 +32,7 @@ type UserQuery struct {
}
type UsersPageRequest struct {
LimitOffestParams
LimitOffsetParams
Order *OrderParams // Параметры сортировки
Query *UserQuery // Параметры выборки
+28
View File
@@ -0,0 +1,28 @@
package entity
const (
SessionStatusAllowed = "ALLOWED"
SessionStatusAllowedRus = "Активная"
SessionStatusExpired = "EXPIRED"
SessionStatusExpiredRus = "Истекшая"
SessionStatusRevoked = "REVOKED"
SessionStatusRevokedRus = "Отмененная"
)
func AuditColumnNames() []string {
return []string{"Пользователь", "Время события", "Действие"}
}
func SessionColumnNames() []string {
return []string{"Пользователь", "Идентификатор", "Дата начала сессии", "Дата окончания сессии", "Статус"}
}
func UserColumnNames() []string {
return []string{"id", "Пользователь", "Описание", "Email", "Роль", "Последняя сессия"}
}
func RoleColumnNames() []string {
return []string{"Действие", "Ключ в системе"}
}
+9 -8
View File
@@ -13,14 +13,15 @@ const (
)
type Role struct {
Id int
Name string
ExternalGroup string
Permissions PermList
Immutable bool
Exclusive bool
CreatedAt time.Time
UpdatedAt time.Time
Id int
Name string
ExternalGroup string
ApplicationGroup string
Permissions PermList
Immutable bool
Exclusive bool
CreatedAt time.Time
UpdatedAt time.Time
}
type PermList []string
+1
View File
@@ -5,6 +5,7 @@ import "time"
type User struct {
OauthUserId *string
Id int64
Roles []int
FirstName string
LastName string
FullName string
+39 -36
View File
@@ -1,6 +1,6 @@
module isp-admin-service
go 1.26.0
go 1.27
require (
github.com/Masterminds/squirrel v1.5.4
@@ -8,11 +8,10 @@ require (
github.com/iancoleman/strcase v0.3.0
github.com/stretchr/testify v1.12.1
github.com/txix-open/bgjob v1.6.0
github.com/txix-open/isp-kit v1.74.1
github.com/txix-open/isp-kit v1.76.0
github.com/txix-open/jsonschema v1.3.0
golang.org/x/crypto v0.55.0
golang.org/x/sync v0.22.0
google.golang.org/grpc v1.83.2
golang.org/x/crypto v0.59.0
golang.org/x/sync v0.25.0
)
require (
@@ -22,61 +21,65 @@ require (
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/coder/websocket v1.8.15 // indirect
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
github.com/getsentry/sentry-go v0.49.0 // indirect
github.com/go-faker/faker/v4 v4.11.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.16 // indirect
github.com/getsentry/sentry-go v0.50.0 // indirect
github.com/go-faker/faker/v4 v4.12.0 // indirect
github.com/go-logr/logr v1.4.4 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 // indirect
github.com/go-playground/locales v0.14.2 // indirect
github.com/go-playground/universal-translator v0.18.2 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/pgx/v5 v5.10.0 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/jackc/pgx/v5 v5.13.0 // indirect
github.com/jackc/puddle/v2 v2.2.4 // indirect
github.com/jmoiron/sqlx v1.4.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.19.2 // indirect
github.com/julienschmidt/httprouter v1.3.0 // indirect
github.com/klauspost/compress v1.20.4 // indirect
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
github.com/leodido/go-urn v1.5.0 // indirect
github.com/mailru/easyjson v0.9.2 // indirect
github.com/mfridman/interpolate v0.0.2 // indirect
github.com/mfridman/interpolate v0.2.0 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pressly/goose/v3 v3.27.3 // indirect
github.com/prometheus/client_golang v1.24.1 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.70.1 // indirect
github.com/prometheus/procfs v0.21.1 // indirect
github.com/pandatix/go-abnf v0.5.5 // indirect
github.com/pressly/goose/v3 v3.30.1 // indirect
github.com/prometheus/client_golang v1.25.0 // indirect
github.com/prometheus/client_model v0.6.3 // indirect
github.com/prometheus/common v0.74.0 // indirect
github.com/prometheus/procfs v0.23.0 // indirect
github.com/robfig/cron/v3 v3.0.1 // indirect
github.com/sethvargo/go-retry v0.4.0 // indirect
github.com/sethvargo/go-retry v0.5.0 // indirect
github.com/txix-open/bellows v1.2.0 // indirect
github.com/txix-open/etp/v4 v4.1.3 // indirect
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb // indirect
github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3 // indirect
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.71.0 // indirect
go.opentelemetry.io/otel v1.46.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0 // indirect
go.opentelemetry.io/otel/metric v1.46.0 // indirect
go.opentelemetry.io/otel/sdk v1.46.0 // indirect
go.opentelemetry.io/otel/trace v1.46.0 // indirect
go.opentelemetry.io/proto/otlp v1.11.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 // indirect
go.opentelemetry.io/otel v1.47.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 // indirect
go.opentelemetry.io/otel/log v1.47.0 // indirect
go.opentelemetry.io/otel/metric v1.47.0 // indirect
go.opentelemetry.io/otel/sdk v1.47.0 // indirect
go.opentelemetry.io/otel/trace v1.47.0 // indirect
go.opentelemetry.io/proto/otlp v1.11.1 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.28.0 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/net v0.58.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/text v0.41.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5 // indirect
go.yaml.in/yaml/v3 v3.0.6 // indirect
golang.org/x/net v0.63.0 // indirect
golang.org/x/sys v0.50.0 // indirect
golang.org/x/text v0.44.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f // indirect
google.golang.org/grpc v1.85.0 // indirect
google.golang.org/protobuf v1.36.12 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
+96 -94
View File
@@ -19,18 +19,18 @@ github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNU
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ=
github.com/getsentry/sentry-go v0.49.0 h1:Ehejknu1l023Ub7QoRBVLAI7g3Jnhqku4oWx4B4Sh5s=
github.com/getsentry/sentry-go v0.49.0/go.mod h1:nuMJAoCfe1u0Bts2ocyNI+TW8HT84vRMqwA5Qq/SKUI=
github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E=
github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4=
github.com/getsentry/sentry-go v0.50.0 h1:gkO59rn/i0RCAXUUTflC5QVbTQGPXbaFabs2olVzc9g=
github.com/getsentry/sentry-go v0.50.0/go.mod h1:+xsDuN+SoRN/xfs1hdq78wnrE3omIZf+FCuh9FOW1C8=
github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=
github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
github.com/go-faker/faker/v4 v4.11.0 h1:HeIFTzafXsgrlxKE2QySGGTQocfGdQ8sGqU2CXvs120=
github.com/go-faker/faker/v4 v4.11.0/go.mod h1:VFIEwWDd16EdYDLF6NJ5gAAzEp7vz5LgKgJ2iZ17Tdg=
github.com/go-faker/faker/v4 v4.12.0 h1:yZXxuoQjxN+C2PVgYoDSHGiD9wj6dX1/Ful4p7QQV0k=
github.com/go-faker/faker/v4 v4.12.0/go.mod h1:VFIEwWDd16EdYDLF6NJ5gAAzEp7vz5LgKgJ2iZ17Tdg=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
@@ -38,15 +38,13 @@ github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-resty/resty/v2 v2.17.2 h1:FQW5oHYcIlkCNrMD2lloGScxcHJ0gkjshV3qcQAyHQk=
github.com/go-resty/resty/v2 v2.17.2/go.mod h1:kCKZ3wWmwJaNc7S29BRtUhJwy7iqmn+2mLtQrOyQlVA=
github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY=
github.com/go-playground/locales v0.14.2/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU=
github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk=
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
github.com/go-sql-driver/mysql v1.10.0 h1:Q+1LV8DkHJvSYAdR83XzuhDaTykuDx0l6fkXxoWCWfw=
github.com/go-sql-driver/mysql v1.10.0/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME=
github.com/go-sql-driver/mysql v1.10.1/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
@@ -54,26 +52,26 @@ github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 h1:/Tnpcb2E0Pz/tN9s3bfEY2Q8ePCEX9iuS+cneUwncnw=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0/go.mod h1:zOBXOsUaBSjKgmH4OGzV1esUpR3oUSCPYVd2cUBjKYY=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 h1:vzlTzzi4tHLa/JQdIE5LeXw6SEX5EVVhq/VPqKHnKOk=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0/go.mod h1:FHXQZnW5pA0txiMr3jApv9uNJzZ+7mYZd+u+PPenCFU=
github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4=
github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds=
github.com/jackc/puddle/v2 v2.2.4 h1:N6Mz6EGB9DL0bz3OEfxJ7eoOpjRHnnjpOh+G8kbLoG8=
github.com/jackc/puddle/v2 v2.2.4/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
github.com/klauspost/compress v1.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8=
github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI=
github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
@@ -90,12 +88,12 @@ github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mailru/easyjson v0.9.2 h1:dX8U45hQsZpxd80nLvDGihsQ/OxlvTkVUXH2r/8cb2M=
github.com/mailru/easyjson v0.9.2/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
github.com/mattn/go-isatty v0.0.23 h1:cYwCQTQf3HB6xUC+BtyCLZNr7IzbOmoZbmssVNzSyiQ=
github.com/mattn/go-isatty v0.0.23/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
github.com/mfridman/interpolate v0.2.0 h1:HM9ID8p6CUxoMJX+fECOtGQ2Mu7TW/GIMPyu48nnvUg=
github.com/mfridman/interpolate v0.2.0/go.mod h1:8SfDy95IaPNnIokZh9mvIppmc3fGl8fx+Gu7uusuO9Q=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
@@ -105,33 +103,35 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g=
github.com/pandatix/go-abnf v0.5.5 h1:EXex5KkRQx4Dm6GnpAcQnIMBs9KiK0uf8p/wq+4t9PM=
github.com/pandatix/go-abnf v0.5.5/go.mod h1:AE0KD3/VNoCjGzc1gqetRKshbI4SYErXQ/8kPenR5mc=
github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4=
github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pressly/goose/v3 v3.27.3 h1:pIglVHjw99r4e/hDHHwbl9vfOsDMqUokfkXo6+n/RxA=
github.com/pressly/goose/v3 v3.27.3/go.mod h1:Dag+xpV6o20HR2LFY1j0q6MDwc3f7vPUFDA77R+0yGY=
github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY=
github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
github.com/rabbitmq/amqp091-go v1.14.0 h1:RSaT7aOKt/OrkVUyswPDW29lnRz9psuGmfZFBmLqLek=
github.com/rabbitmq/amqp091-go v1.14.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
github.com/pressly/goose/v3 v3.30.1 h1:KO28meBdbAUIdMbTP7bl9dp1FYZGXcYWb2O7miT09lE=
github.com/pressly/goose/v3 v3.30.1/go.mod h1:CHGwuG2acDerUaXwz2i5T18VSauXpYDiL4WxzDvcOIM=
github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0=
github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk=
github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo=
github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM=
github.com/prometheus/common v0.74.0 h1:6iYW8MsYvmEnXFD9zLGgF0qmReaRhs3OMONu1c/nrLI=
github.com/prometheus/common v0.74.0/go.mod h1:i/02C+FCst5B1etKgWesNrD49n+onplJCqUCtUKkOeA=
github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4=
github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk=
github.com/rabbitmq/amqp091-go v1.17.0 h1:6KmTqrnJq93cGIE3Q3UnXgsqw6NtLu8MNfFoIbfBAIQ=
github.com/rabbitmq/amqp091-go v1.17.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/sethvargo/go-retry v0.4.0 h1:9qy1OoIAxBL+gBYnkTnTnWle5wlfsXQlwRzIbbpdqPw=
github.com/sethvargo/go-retry v0.4.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY=
github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
@@ -153,12 +153,12 @@ github.com/txix-open/etp/v4 v4.1.3 h1:u9ZyU2yKGgoQ1/DSaElhazWm8xASdqGEdWjoJ2xQlf
github.com/txix-open/etp/v4 v4.1.3/go.mod h1:9GK+Aje8BmLFq8Hk4j6Qb976LdU9WECCWAuLK1vAKgM=
github.com/txix-open/grmq v1.12.0 h1:lSPYvwLfTL0+b0xDQmuuN6RaKS3NCEJNK9ccWpOWa8Y=
github.com/txix-open/grmq v1.12.0/go.mod h1:6m9CCTQao/HAFalu5rFOZGJ5KLEP6WzzIwj80Ml3KGE=
github.com/txix-open/isp-kit v1.74.1 h1:2WQl1+e6E1TXcgkm554kYpiyORgZiyJa/zQIks4cUCw=
github.com/txix-open/isp-kit v1.74.1/go.mod h1:i4g+hgfVQAXa02kHqr104TqYEsiW2em17RZF0KjkB78=
github.com/txix-open/isp-kit v1.76.0 h1:kqhX2DuoTfeW7BIshedG26TRIfOgX0QOInm606ssGVg=
github.com/txix-open/isp-kit v1.76.0/go.mod h1:hR9iAlh3x9gEg5GfALrrkN/2SbGkgZQCmwO2GZWjC1M=
github.com/txix-open/jsonschema v1.3.0 h1:XGuOTg22G7PdqfKypjajM20/i5FyGfFYsJKmheebKi4=
github.com/txix-open/jsonschema v1.3.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00=
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb h1:UJgT4u/QMv5QHKOQeJ7igShHa36c2/vIRqJiRLdDlf0=
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb/go.mod h1:0biAFE0bgbcKeBBAwgEDhbZz6uT1vuSETCrFQlv2RiA=
github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3 h1:1jE11HLmMHDYYAcE+UmQ5VHgz4stzz0+daJbDWS+sEs=
github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3/go.mod h1:Yf41v210LFyYAj+tGmDh7PHdGsTaZjdBzHG0ptUvihw=
github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc=
github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw=
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
@@ -170,54 +170,56 @@ github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.71.0 h1:oFNJW32h2SXnET7XXstgT7pVh4vN+jW+GfiIaBguIZE=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.71.0/go.mod h1:+H3sPOFwag14eMHTPMElZtV0e4YfVZ/85KgrKUCB5FI=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU=
go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc=
go.opentelemetry.io/otel v1.46.0/go.mod h1:Gj3SEScelsNC45tp4nSxRYlS+f5iez7W8XPMCt905kE=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 h1:OFnwLJr+pF3iHrlGSzbxyuo6/6HyBlnlN1CWEJmBVcw=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0/go.mod h1:716wFneO0ov19A2beH5hjfh9AK5z/VWNAtDijp1Y0/g=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0 h1:KrC1YrQeSt46ITMWAbgQx1M1eV1/1TKzttrBzymPmss=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0/go.mod h1:zDSEzoEqsOrgBeGvH66KRgxh90VonFyJqBHA0Pk3+rM=
go.opentelemetry.io/otel/metric v1.46.0 h1:yBnkXvgV7AXFILZc5K6IZe/CBFF3OS7BJ8ov6/lj0K8=
go.opentelemetry.io/otel/metric v1.46.0/go.mod h1:iPmdWqifKUdzziPkvvzIJXITl56fQx2mGM/DHLB3/2o=
go.opentelemetry.io/otel/sdk v1.46.0 h1:h5CNQQjEbuQXY/JfZtgt3i7HVFV3aHPO2OAwO2eTYPI=
go.opentelemetry.io/otel/sdk v1.46.0/go.mod h1:GAERFXFt5SYCEB+YiKUbMBeza6UaDH7GmGOZEfh2gSM=
go.opentelemetry.io/otel/sdk/metric v1.46.0 h1:0piZ26EG4RBfebb2jhDH6ERCYHoVWduc3kLgPCwSnSE=
go.opentelemetry.io/otel/sdk/metric v1.46.0/go.mod h1:I1PbKrdVc8Qu8HYVDNtqVIwLwjNrhsV/uFuxfwg8mO4=
go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c=
go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI=
go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk=
go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 h1:jva1c3z2ZFEQ5sTvnLG2tBALNehO+QvdXKQii6eKRoo=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0/go.mod h1:3pjFS5EnOVfjvYO6/NMdtJFHFQR+8uiGtrZ965nZP4w=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0/go.mod h1:tOsftB4SslBwwErVEPaenU2RpThXWPIU8DoJHEC4dyw=
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 h1:aXZXsZ012wOgVkqaiQv+Z/d8V0xKjmg70F6m4CE94lc=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0/go.mod h1:ziu1gUIJhAaxM3EV1e3Ralk5AAyL1UOYz3lJJ4VSI38=
go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI=
go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw=
go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY=
go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU=
go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I=
go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0=
go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw=
go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw=
go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM=
go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0=
go.opentelemetry.io/proto/otlp v1.11.1 h1:SCrPqH9NE5CmBrOqpjNCiT0X5mGwMyGERXdogfR7Yjw=
go.opentelemetry.io/proto/otlp v1.11.1/go.mod h1:wq8W4aSf6bOy8RZyESOeQFr9Pu7wydWX/TY4sgvrTPg=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
go.yaml.in/yaml/v2 v2.4.5 h1:a5nxWvYi94DRl6QSLlTbLpVmutgx2qg8EVjnJtuFpwI=
go.yaml.in/yaml/v2 v2.4.5/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0=
golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig=
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5 h1:izFU9hz7aeLI/Mi1J0991ae+xcwRLr7hTqWnB/9aIIU=
google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5/go.mod h1:3LhxRw4YYkf+ylAfgaY9JlVLFKhokkCV8duhLLe7+t0=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5 h1:1VUiZAXyC+zmiFYi+WLtBzr68Cj8wOofHjjrA/kkizc=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5/go.mod h1:DjtHYE8FKJLivXcBEjGwndXfIC23G0VpXiXKqG179uA=
google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f h1:7CbYDSDM5xqpq8v2tNm+Q057COf1lvA0gorVk+304tY=
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f/go.mod h1:CPxXEEQ1S9iJmInAF/8MNc8tKWnya8I8Kni9Zh2hV0M=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f h1:aDW6Vb2T1K0xbAgW+ED8iz39WlgjjX/OKiNh6tXv/+g=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw=
google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
@@ -228,11 +230,11 @@ gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYs
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/libc v1.74.3 h1:a4J+Z8aVaxPyjyxRAdJzw246PqpcFGvVPnfT/AuM5Ws=
modernc.org/libc v1.74.3/go.mod h1:4H7h/MJ8wnjL8RAbp9v3OXgnk22X7MouHIhDbvP3gj4=
modernc.org/libc v1.80.2 h1:3+a4fJZvvzg920ZC0mOepnKPGn7cqCaVeDxm/UnrM1A=
modernc.org/libc v1.80.2/go.mod h1:pvo25Rs3OJEbDqhUV9jdEGevxeLJrJeDmNid/AcQV1g=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/sqlite v1.54.0 h1:JCxR4qwkJvOaqAoYcgDoO25Nc+ROg6EJ2LfBVzdrgog=
modernc.org/sqlite v1.54.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw=
modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/sqlite v1.62.0 h1:gMaCjSM1qpl+iOjiWhR1LYP3zqrYDI+5GYLGt6veP2g=
modernc.org/sqlite v1.62.0/go.mod h1:Jzjh1mt4s0HuQ0KvtB1LIuHiGRmU2D5pgj8dUhW7/SE=
+7 -7
View File
@@ -12,18 +12,18 @@ import (
var version = "1.0.0"
// @title isp-admin-service
// @version 1.0.0
// @description сервис управления администраторами
// @title isp-admin-service
// @version 1.0.0
// @description сервис управления администраторами
// @license.name GNU GPL v3.0
// @license.name GNU GPL v3.0
// @host localhost:9000
// @BasePath /api/admin
// @host localhost:9000
// @BasePath /api/admin
//go:generate swag init -pd -ot json -eot json
func main() {
boot := bootstrap.New(version, conf.Remote{}, cluster.Endpoints(routes.EndpointDescriptors()), cluster.GrpcTransport)
boot := bootstrap.New(version, conf.Remote{}, cluster.Endpoints(routes.EndpointDescriptors()), cluster.HttpTransport)
app := boot.App
logger := app.Logger()
@@ -0,0 +1,5 @@
-- +goose Up
ALTER TABLE roles ADD COLUMN application_group TEXT NOT NULL DEFAULT '';
-- +goose Down
ALTER TABLE roles DROP COLUMN application_group;
+20 -4
View File
@@ -25,6 +25,7 @@ const (
updatedAtRolesColumn = "updated_at"
permissionsRolesColumn = "permissions"
externalGroupRolesColumn = "external_group"
applicationGroupColumn = "application_group"
immutableRolesColumn = "immutable"
exclusiveRolesColumn = "exclusive"
)
@@ -37,7 +38,7 @@ func (r Role) GetRoleByIds(ctx context.Context, id []int) ([]entity.Role, error)
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.GetRoleByIds")
q, args, err := query.New().
Select("id, name, external_group, permissions, created_at, updated_at").
Select("id, name, external_group, application_group, permissions, created_at, updated_at").
From("roles").
Where(squirrel.Eq{"id": id}).
ToSql()
@@ -67,6 +68,7 @@ func (r Role) GetRoleByName(ctx context.Context, name string) (*entity.Role, err
updatedAtRolesColumn,
permissionsRolesColumn,
externalGroupRolesColumn,
applicationGroupColumn,
immutableRolesColumn,
exclusiveRolesColumn,
).
@@ -101,6 +103,7 @@ func (r Role) GetRolesByExternalGroup(ctx context.Context, groups []string) ([]e
updatedAtRolesColumn,
permissionsRolesColumn,
externalGroupRolesColumn,
applicationGroupColumn,
immutableRolesColumn,
exclusiveRolesColumn,
).
@@ -122,7 +125,7 @@ func (r Role) GetRolesByExternalGroup(ctx context.Context, groups []string) ([]e
func (r Role) All(ctx context.Context) ([]entity.Role, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.All")
q := "select id, name, external_group, permissions, immutable, exclusive, created_at, updated_at from roles order by created_at"
q := "select id, name, external_group, application_group, permissions, immutable, exclusive, created_at, updated_at from roles order by created_at"
roles := make([]entity.Role, 0)
err := r.db.Select(ctx, &roles, q)
if err != nil {
@@ -131,12 +134,24 @@ func (r Role) All(ctx context.Context) ([]entity.Role, error) {
return roles, nil
}
func (r Role) AllWithFilter(ctx context.Context, applicationGroup string) ([]entity.Role, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.AllWithFilter")
roles := make([]entity.Role, 0)
err := r.db.Select(ctx, &roles, `
select id, name, external_group, application_group, permissions, immutable, exclusive, created_at, updated_at
from roles where application_group=$1 order by created_at`, applicationGroup)
if err != nil {
return nil, errors.WithMessage(err, "select all roles")
}
return roles, nil
}
func (r Role) InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.InsertRole")
q, args, err := query.New().Insert("roles").
Columns("name", "permissions", "external_group").
Values(role.Name, role.Permissions, role.ExternalGroup).
Columns("name", "permissions", "external_group", "application_group").
Values(role.Name, role.Permissions, role.ExternalGroup, role.ApplicationGroup).
Suffix("RETURNING *").ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
@@ -158,6 +173,7 @@ func (r Role) Update(ctx context.Context, role entity.Role) (*entity.Role, error
Set("name", role.Name).
Set("permissions", role.Permissions).
Set("external_group", role.ExternalGroup).
Set("application_group", role.ApplicationGroup).
Where(squirrel.Eq{"id": role.Id}).
Suffix("RETURNING *").ToSql()
if err != nil {
+159 -102
View File
@@ -3,12 +3,12 @@ package routes
import (
"isp-admin-service/controller"
"isp-admin-service/docs"
"net/http"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/common_endpoints"
"github.com/txix-open/isp-kit/grpc"
"github.com/txix-open/isp-kit/grpc/endpoint"
"github.com/txix-open/isp-kit/grpc/isp"
httpEndpoint "github.com/txix-open/isp-kit/http/endpoint"
"github.com/txix-open/isp-kit/http/router"
)
type Controllers struct {
@@ -21,6 +21,7 @@ type Controllers struct {
Role controller.Role
Permissions controller.Permissions
UiSettings controller.UiSettings
Download controller.Download
}
func EndpointDescriptors() []cluster.EndpointDescriptor {
@@ -30,13 +31,13 @@ func EndpointDescriptors() []cluster.EndpointDescriptor {
)
}
func Handler(wrapper endpoint.Wrapper, c Controllers) isp.BackendServiceServer { // nolint:ireturn
muxer := grpc.NewMux()
func Handler(wrapper httpEndpoint.Wrapper, c Controllers) *router.Router { // nolint:ireturn
muxer := router.New()
for _, descriptor := range endpointDescriptors(c) {
muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler))
muxer.Handler(descriptor.HttpMethod, "/"+descriptor.Path, wrapper.Endpoint(descriptor.Handler))
}
for _, descriptor := range commonEndpoints() {
muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler))
muxer.Handler(descriptor.HttpMethod, "/"+descriptor.Path, wrapper.Endpoint(descriptor.Handler))
}
return muxer
}
@@ -45,153 +46,209 @@ func Handler(wrapper endpoint.Wrapper, c Controllers) isp.BackendServiceServer {
func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "admin/auth/login",
Inner: false,
Handler: c.Auth.Login,
Path: "admin/auth/login",
Inner: false,
Handler: c.Auth.Login,
HttpMethod: http.MethodPost,
},
{
Path: "admin/auth/login_with_oauth",
Inner: false,
Handler: c.Auth.LoginWithOauth,
Path: "admin/auth/login_with_oauth",
Inner: false,
Handler: c.Auth.LoginWithOauth,
HttpMethod: http.MethodPost,
},
{
Path: "admin/auth/logout",
Inner: true,
Handler: c.Auth.Logout,
Path: "admin/auth/logout",
Inner: true,
Handler: c.Auth.Logout,
HttpMethod: http.MethodPost,
},
{
Path: "admin/auth/logout_with_reason",
Inner: true,
Handler: c.Auth.LogoutWithReason,
Path: "admin/auth/logout_with_reason",
Inner: true,
Handler: c.Auth.LogoutWithReason,
HttpMethod: http.MethodPost,
},
{
Path: "admin/user/get_profile",
Inner: true,
Handler: c.User.GetProfile,
Path: "admin/user/get_profile",
Inner: true,
Handler: c.User.GetProfile,
HttpMethod: http.MethodPost,
},
{
Path: "admin/user/get_design",
Inner: true,
Handler: c.Customization.GetUIDesign,
Path: "admin/user/get_design",
Inner: true,
Handler: c.Customization.GetUIDesign,
HttpMethod: http.MethodPost,
},
{
Path: "admin/user/get_users",
Inner: true,
Handler: c.User.GetUsers,
Path: "admin/user/get_users",
Inner: true,
Handler: c.User.GetUsers,
HttpMethod: http.MethodPost,
},
{
Path: "admin/user/get_all_users",
Inner: true,
Handler: c.User.GetAllUsers,
Path: "admin/user/get_all_users",
Inner: true,
Handler: c.User.GetAllUsers,
HttpMethod: http.MethodPost,
},
{
Path: "admin/user/create_user",
Inner: true,
Extra: cluster.RequireAdminPermission("user_create"),
Handler: c.User.CreateUser,
Path: "admin/user/create_user",
Inner: true,
Extra: cluster.RequireAdminPermission("user_create"),
Handler: c.User.CreateUser,
HttpMethod: http.MethodPost,
},
{
Path: "admin/user/update_user",
Inner: true,
Extra: cluster.RequireAdminPermission("user_update"),
Handler: c.User.UpdateUser,
Path: "admin/user/update_user",
Inner: true,
Extra: cluster.RequireAdminPermission("user_update"),
Handler: c.User.UpdateUser,
HttpMethod: http.MethodPost,
},
{
Path: "admin/user/delete_user",
Inner: true,
Extra: cluster.RequireAdminPermission("user_delete"),
Handler: c.User.DeleteUser,
Path: "admin/user/delete_user",
Inner: true,
Extra: cluster.RequireAdminPermission("user_delete"),
Handler: c.User.DeleteUser,
HttpMethod: http.MethodPost,
},
{
Path: "admin/user/block_user",
Inner: true,
Extra: cluster.RequireAdminPermission("user_block"),
Handler: c.User.Block,
Path: "admin/user/block_user",
Inner: true,
Extra: cluster.RequireAdminPermission("user_block"),
Handler: c.User.Block,
HttpMethod: http.MethodPost,
},
{
Path: "admin/user/get_by_id",
Inner: true,
Handler: c.User.GetById,
Path: "admin/user/get_by_id",
Inner: true,
Handler: c.User.GetById,
HttpMethod: http.MethodPost,
},
{
Path: "admin/user/change_password",
Inner: true,
Handler: c.User.ChangePassword,
Path: "admin/user/change_password",
Inner: true,
Handler: c.User.ChangePassword,
HttpMethod: http.MethodPost,
},
{
Path: "admin/role/all",
Inner: true,
Extra: cluster.RequireAdminPermission("role_view"),
Handler: c.Role.All,
Path: "admin/role/all",
Inner: true,
Extra: cluster.RequireAdminPermission("role_view"),
Handler: c.Role.All,
HttpMethod: http.MethodPost,
},
{
Path: "admin/user/get_permissions",
Inner: true,
Extra: cluster.RequireAdminPermission("role_view"),
Handler: c.Permissions.GetPermissions,
Path: "admin/user/get_permissions",
Inner: true,
Extra: cluster.RequireAdminPermission("role_view"),
Handler: c.Permissions.GetPermissions,
HttpMethod: http.MethodPost,
},
{
Path: "admin/role/create",
Inner: true,
Extra: cluster.RequireAdminPermission("role_add"),
Handler: c.Role.CreateRole,
Path: "admin/role/create",
Inner: true,
Extra: cluster.RequireAdminPermission("role_add"),
Handler: c.Role.CreateRole,
HttpMethod: http.MethodPost,
},
{
Path: "admin/role/update",
Inner: true,
Extra: cluster.RequireAdminPermission("role_update"),
Handler: c.Role.UpdateRole,
Path: "admin/role/update",
Inner: true,
Extra: cluster.RequireAdminPermission("role_update"),
Handler: c.Role.UpdateRole,
HttpMethod: http.MethodPost,
},
{
Path: "admin/role/delete",
Inner: true,
Extra: cluster.RequireAdminPermission("role_delete"),
Handler: c.Role.DeleteRole,
Path: "admin/role/delete",
Inner: true,
Extra: cluster.RequireAdminPermission("role_delete"),
Handler: c.Role.DeleteRole,
HttpMethod: http.MethodPost,
},
{
Path: "admin/session/all",
Inner: true,
Extra: cluster.RequireAdminPermission("session_view"),
Handler: c.Session.All,
Path: "admin/session/all",
Inner: true,
Extra: cluster.RequireAdminPermission("session_view"),
Handler: c.Session.All,
HttpMethod: http.MethodPost,
},
{
Path: "admin/session/revoke",
Inner: true,
Extra: cluster.RequireAdminPermission("session_revoke"),
Handler: c.Session.Revoke,
Path: "admin/session/revoke",
Inner: true,
Extra: cluster.RequireAdminPermission("session_revoke"),
Handler: c.Session.Revoke,
HttpMethod: http.MethodPost,
},
{
Path: "admin/log/all",
Inner: true,
Extra: cluster.RequireAdminPermission("security_log_view"),
Handler: c.Audit.All,
Path: "admin/log/all",
Inner: true,
Extra: cluster.RequireAdminPermission("security_log_view"),
Handler: c.Audit.All,
HttpMethod: http.MethodPost,
},
{
Path: "admin/log/events",
Inner: true,
Extra: cluster.RequireAdminPermission("audit_management_view"),
Handler: c.Audit.Events,
Path: "admin/log/events",
Inner: true,
Extra: cluster.RequireAdminPermission("audit_management_view"),
Handler: c.Audit.Events,
HttpMethod: http.MethodPost,
},
{
Path: "admin/log/set_events",
Inner: true,
Extra: cluster.RequireAdminPermission("audit_management_view"),
Handler: c.Audit.SetEvents,
Path: "admin/log/set_events",
Inner: true,
Extra: cluster.RequireAdminPermission("audit_management_view"),
Handler: c.Audit.SetEvents,
HttpMethod: http.MethodPost,
},
{
Path: "admin/secure/authenticate",
Inner: true,
Handler: c.Secure.Authenticate,
Path: "admin/secure/authenticate",
Inner: true,
Handler: c.Secure.Authenticate,
HttpMethod: http.MethodPost,
},
{
Path: "admin/secure/authorize",
Inner: true,
Handler: c.Secure.Authorize,
Path: "admin/secure/authorize",
Inner: true,
Handler: c.Secure.Authorize,
HttpMethod: http.MethodPost,
},
{
Path: "admin/ui_settings/oauth",
Inner: false,
Handler: c.UiSettings.OauthSettings,
Path: "admin/ui_settings/oauth",
Inner: false,
Handler: c.UiSettings.OauthSettings,
HttpMethod: http.MethodPost,
},
// download
{
Path: "user/download",
Inner: true,
Extra: cluster.RequireAdminPermission("data_download"),
Handler: c.Download.Users,
HttpMethod: http.MethodPost,
},
{
Path: "session/download",
Inner: true,
Extra: cluster.RequireAdminPermission("data_download"),
Handler: c.Download.Sessions,
HttpMethod: http.MethodPost,
},
{
Path: "log/download",
Inner: true,
Extra: cluster.RequireAdminPermission("data_download"),
Handler: c.Download.Audit,
HttpMethod: http.MethodPost,
},
{
Path: "role/download",
Inner: true,
Extra: cluster.RequireAdminPermission("data_download"),
Handler: c.Download.Roles,
HttpMethod: http.MethodPost,
},
}
}
+325
View File
@@ -0,0 +1,325 @@
package service
import (
"context"
"encoding/csv"
"fmt"
"net/http"
"slices"
"strconv"
"strings"
"time"
"isp-admin-service/domain"
"isp-admin-service/entity"
"github.com/txix-open/isp-kit/errors"
)
const (
requestLimit = 1000
foundSymbol = "+"
notFoundSymbol = "-"
)
type Download struct {
auditService Audit
userService User
tokenService Token
roleService Role
permissionService Permission
loc *time.Location
}
func NewDownload(
auditService Audit,
userService User,
tokenService Token,
roleService Role,
permissionService Permission,
) Download {
loc, _ := time.LoadLocation("Europe/Moscow")
return Download{
auditService: auditService,
userService: userService,
tokenService: tokenService,
roleService: roleService,
permissionService: permissionService,
loc: loc,
}
}
func (s Download) DownloadAudit(ctx context.Context, req domain.AuditPageRequest, w http.ResponseWriter) error {
req.Limit = requestLimit
req.Offset = 0
response, err := s.auditService.All(ctx, req)
if err != nil {
return errors.WithMessage(err, "get audit")
}
if response.TotalCount == 0 {
return nil
}
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", getCsvFileName("Audit")))
w.Header().Set("content-type", "application/octet-stream; charset=utf-8")
w.Header().Set("transfer-encoding", "chunked")
csvWriter := csv.NewWriter(w)
defer csvWriter.Flush()
err = writeCsvLine(csvWriter, entity.AuditColumnNames())
if err != nil {
return errors.WithMessage(err, "write auditColumns to csv")
}
userById, err := s.getUsersList(ctx)
if err != nil {
return errors.WithMessage(err, "get users list")
}
itemsCount := len(response.Items)
for {
for _, audit := range response.Items {
username := getUsername(userById, audit.UserId)
row := []string{username, s.formatTime(&audit.CreatedAt, false), audit.Message}
err = writeCsvLine(csvWriter, row)
if err != nil {
return errors.WithMessage(err, "write audit row to csv")
}
}
if itemsCount >= response.TotalCount {
break
}
req.Offset += requestLimit
response, err = s.auditService.All(ctx, req)
if err != nil {
return errors.WithMessage(err, "get audit")
}
itemsCount += len(response.Items)
}
return nil
}
func (s Download) DownloadSessions(ctx context.Context, req domain.SessionPageRequest, w http.ResponseWriter) error {
req.Limit = requestLimit
req.Offset = 0
response, err := s.tokenService.All(ctx, req)
if err != nil {
return errors.WithMessage(err, "get sessions")
}
if response.TotalCount == 0 {
return nil
}
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", getCsvFileName("Sessions")))
w.Header().Set("content-type", "application/octet-stream; charset=utf-8")
w.Header().Set("transfer-encoding", "chunked")
csvWriter := csv.NewWriter(w)
defer csvWriter.Flush()
err = writeCsvLine(csvWriter, entity.SessionColumnNames())
if err != nil {
return errors.WithMessage(err, "write sessionColumns to csv")
}
userById, err := s.getUsersList(ctx)
if err != nil {
return errors.WithMessage(err, "get users list")
}
itemsCount := len(response.Items)
for {
for _, session := range response.Items {
row := []string{
getUsername(userById, session.UserId),
strconv.Itoa(session.Id),
s.formatTime(&session.CreatedAt, false),
s.formatTime(&session.ExpiredAt, false),
session.StatusRus()}
err = writeCsvLine(csvWriter, row)
if err != nil {
return errors.WithMessage(err, "write session row to csv")
}
}
if itemsCount >= response.TotalCount {
break
}
req.Offset += requestLimit
response, err = s.tokenService.All(ctx, req)
if err != nil {
return errors.WithMessage(err, "get sessions")
}
itemsCount += len(response.Items)
}
return nil
}
func (s Download) DownloadUsers(ctx context.Context, req domain.UsersPageRequest, w http.ResponseWriter) error {
req.Limit = requestLimit
req.Offset = 0
users, err := s.userService.GetUsers(ctx, req)
if err != nil {
return errors.WithMessage(err, "get users")
}
roles, err := s.roleService.All(ctx, domain.RoleAllRequest{})
if err != nil {
return errors.WithMessage(err, "get roles")
}
if len(users.Items) == 0 {
return nil
}
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", getCsvFileName("Users")))
w.Header().Set("content-type", "application/octet-stream; charset=utf-8")
w.Header().Set("transfer-encoding", "chunked")
csvWriter := csv.NewWriter(w)
defer csvWriter.Flush()
err = writeCsvLine(csvWriter, entity.UserColumnNames())
if err != nil {
return errors.WithMessage(err, "write userColumns to csv")
}
for _, user := range users.Items {
row := []string{strconv.Itoa(int(user.Id)),
user.FullName,
user.Description,
user.Email,
getRoleNamesByIds(roles, user.Roles),
s.formatTime(user.LastSessionCreatedAt, true)}
err = writeCsvLine(csvWriter, row)
if err != nil {
return errors.WithMessage(err, "write user row to csv")
}
}
return nil
}
func (s Download) DownloadRoles(ctx context.Context, w http.ResponseWriter) error {
roles, err := s.roleService.All(ctx, domain.RoleAllRequest{})
if err != nil {
return errors.WithMessage(err, "get roles")
}
perms := s.permissionService.All(ctx)
if len(perms) == 0 {
return nil
}
columns := entity.RoleColumnNames()
for _, role := range roles {
columns = append(columns, role.Name)
}
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", getCsvFileName("Roles")))
w.Header().Set("content-type", "application/octet-stream; charset=utf-8")
w.Header().Set("transfer-encoding", "chunked")
csvWriter := csv.NewWriter(w)
defer csvWriter.Flush()
err = writeCsvLine(csvWriter, columns)
if err != nil {
return errors.WithMessage(err, "write role columns to csv")
}
for _, perm := range perms {
row := []string{perm.Name, perm.Key}
for _, role := range roles {
if slices.Contains(role.Permissions, perm.Key) {
row = append(row, foundSymbol)
} else {
row = append(row, notFoundSymbol)
}
}
err = writeCsvLine(csvWriter, row)
if err != nil {
return errors.WithMessage(err, "write role row to csv")
}
}
return nil
}
func (s Download) getUsersList(ctx context.Context) (map[int]domain.User, error) {
users, err := s.userService.GetAllUsers(ctx)
if err != nil {
return nil, errors.WithMessage(err, "get users")
}
userById := make(map[int]domain.User)
for _, user := range users.Items {
userById[int(user.Id)] = user
}
return userById, nil
}
func getUsername(userById map[int]domain.User, userId int) string {
user, ok := userById[userId]
if !ok {
return ""
}
return user.FullName
}
func getRoleNamesByIds(roles []domain.Role, roleIds []int) string {
names := make([]string, 0)
for _, role := range roles {
if slices.Contains(roleIds, role.Id) {
names = append(names, role.Name)
}
}
return strings.Join(names, ", ")
}
func writeCsvLine(csvWriter *csv.Writer, line []string) error {
err := csvWriter.Write(line)
if err != nil {
return errors.WithMessage(err, "write line to csv")
}
return nil
}
func getCsvFileName(pageName string) string {
return fmt.Sprintf("%s_%s.%s", pageName, time.Now().Format("02-01-2006_15:04:05"), "csv")
}
func (s Download) formatTime(t *time.Time, onlyDate bool) string {
if t == nil {
return ""
}
if onlyDate {
return t.In(s.loc).Format("02-01-2006")
}
return t.In(s.loc).Format("02-01-2006 15:04:05")
}
+3 -3
View File
@@ -11,12 +11,12 @@ type Permission struct {
permissions []domain.Permission
}
func NewPermission(permissions []conf.Permission) *Permission {
return &Permission{
func NewPermission(permissions []conf.Permission) Permission {
return Permission{
permissions: toDomain(permissions),
}
}
func (s *Permission) All(_ context.Context) []domain.Permission {
func (s Permission) All(_ context.Context) []domain.Permission {
return s.permissions
}
+46 -29
View File
@@ -13,6 +13,7 @@ import (
type roleRoleRepo interface {
All(ctx context.Context) ([]entity.Role, error)
AllWithFilter(ctx context.Context, applicationGroup string) ([]entity.Role, error)
InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error)
Update(ctx context.Context, role entity.Role) (*entity.Role, error)
Delete(ctx context.Context, id int) error
@@ -32,8 +33,17 @@ func NewRole(roleRepo roleRoleRepo, audit auditService) Role {
}
}
func (u Role) All(ctx context.Context) ([]domain.Role, error) {
roles, err := u.roleRepo.All(ctx)
func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error) {
var (
roles []entity.Role
err error
)
switch {
case req.ApplicationGroup != nil:
roles, err = u.roleRepo.AllWithFilter(ctx, *req.ApplicationGroup)
default:
roles, err = u.roleRepo.All(ctx)
}
if err != nil {
return nil, errors.WithMessage(err, "get all roles")
}
@@ -58,9 +68,10 @@ func (u Role) Create(ctx context.Context, req domain.CreateRoleRequest, adminId
}
role, err = u.roleRepo.InsertRole(ctx, entity.Role{
Name: req.Name,
ExternalGroup: req.ExternalGroup,
Permissions: req.Permissions,
Name: req.Name,
ExternalGroup: req.ExternalGroup,
ApplicationGroup: req.ApplicationGroup,
Permissions: req.Permissions,
})
if err != nil {
@@ -69,13 +80,15 @@ func (u Role) Create(ctx context.Context, req domain.CreateRoleRequest, adminId
slices.Sort(role.Permissions)
diff := diffToString(map[string]any{
"Название": "",
"Группа ЕСК": "",
"Разрешения": []int{},
"Название": "",
"Группа ЕСК": "",
"Группа приложений": "",
"Разрешения": []int{},
}, map[string]any{
"Название": role.Name,
"Группа ЕСК": role.ExternalGroup,
"Разрешения": role.Permissions,
"Название": role.Name,
"Группа ЕСК": role.ExternalGroup,
"Группа приложений": role.ApplicationGroup,
"Разрешения": role.Permissions,
})
u.auditService.SaveAuditAsync(ctx, adminId,
fmt.Sprintf("Роль. Создание новой роли %s. Причина: %s. \n %s", req.Name, req.ChangeMessage, diff),
@@ -106,10 +119,11 @@ func (u Role) Update(ctx context.Context, req domain.UpdateRoleRequest, adminId
oldRole := roles[0]
role, err := u.roleRepo.Update(ctx, entity.Role{
Id: req.Id,
Name: req.Name,
ExternalGroup: req.ExternalGroup,
Permissions: req.Permissions,
Id: req.Id,
Name: req.Name,
ExternalGroup: req.ExternalGroup,
ApplicationGroup: req.ApplicationGroup,
Permissions: req.Permissions,
})
if err != nil {
@@ -119,13 +133,15 @@ func (u Role) Update(ctx context.Context, req domain.UpdateRoleRequest, adminId
slices.Sort(oldRole.Permissions)
slices.Sort(role.Permissions)
diff := diffToString(map[string]any{
"Название": oldRole.Name,
"Группа ЕСК": oldRole.ExternalGroup,
"Разрешения": oldRole.Permissions,
"Название": oldRole.Name,
"Группа ЕСК": oldRole.ExternalGroup,
"Группа приложений": oldRole.ApplicationGroup,
"Разрешения": oldRole.Permissions,
}, map[string]any{
"Название": role.Name,
"Группа ЕСК": role.ExternalGroup,
"Разрешения": role.Permissions,
"Название": role.Name,
"Группа ЕСК": role.ExternalGroup,
"Группа приложений": role.ApplicationGroup,
"Разрешения": role.Permissions,
})
u.auditService.SaveAuditAsync(ctx, adminId,
fmt.Sprintf("Роль. Изменение роли %s. Причина: %s. \n %s", req.Name, req.ChangeMessage, diff),
@@ -148,13 +164,14 @@ func (u Role) Delete(ctx context.Context, req domain.DeleteRoleRequest, adminId
func (u Role) toDomain(role entity.Role) domain.Role {
return domain.Role{
Id: role.Id,
Name: role.Name,
ExternalGroup: role.ExternalGroup,
Permissions: role.Permissions,
Immutable: role.Immutable,
Exclusive: role.Exclusive,
CreatedAt: role.CreatedAt,
UpdatedAt: role.UpdatedAt,
Id: role.Id,
Name: role.Name,
ExternalGroup: role.ExternalGroup,
ApplicationGroup: role.ApplicationGroup,
Permissions: role.Permissions,
Immutable: role.Immutable,
Exclusive: role.Exclusive,
CreatedAt: role.CreatedAt,
UpdatedAt: role.UpdatedAt,
}
}
+30 -32
View File
@@ -1,6 +1,7 @@
package tests_test
import (
"net/http"
"testing"
"time"
@@ -12,13 +13,10 @@ import (
"github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/dbx"
"github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/http/httpcli"
"github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/grpct"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/txix-open/isp-kit/test/httpt"
)
func TestAuditSuite(t *testing.T) {
@@ -31,7 +29,7 @@ type AuditSuite struct {
test *test.Test
db *dbt.TestDb
grpcCli *client.Client
httpCli *httpcli.Client
}
func (s *AuditSuite) SetupTest() {
@@ -75,20 +73,20 @@ func (s *AuditSuite) SetupTest() {
s.Require().NoError(err)
s.insertAuditLogs()
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
s.grpcCli = apiCli
server, cli := httpt.TestServer(s.test, cfg.Handler)
s.httpCli = cli
testInstance.T().Cleanup(func() {
server.Shutdown()
server.Close()
})
}
func (s *AuditSuite) Test_Events_DefaultEvents() {
response := make([]domain.AuditEvent, 0)
err := s.grpcCli.
Invoke("admin/log/events").
err := s.httpCli.
Post("admin/log/events").
JsonResponseBody(&response).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
expectedEventList := map[string]string{
@@ -123,10 +121,10 @@ func (s *AuditSuite) Test_Events_SortEvents() {
s.Require().NoError(err)
response := make([]domain.AuditEvent, 0)
err = s.grpcCli.
Invoke("admin/log/events").
err = s.httpCli.
Post("admin/log/events").
JsonResponseBody(&response).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
expectedSort := []bool{
@@ -139,13 +137,13 @@ func (s *AuditSuite) Test_Events_SortEvents() {
}
func (s *AuditSuite) Test_SetEvents_HappyPath() {
err := s.grpcCli.
Invoke("admin/log/set_events").
err := s.httpCli.
Post("admin/log/set_events").
JsonRequestBody([]domain.SetAuditEvent{
{Event: entity.EventUserChanged, Enabled: true},
{Event: entity.EventRoleChanged, Enabled: false},
}).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
expectedEventList := map[string]bool{
@@ -169,24 +167,24 @@ func (s *AuditSuite) Test_SetEvents_HappyPath() {
}
func (s *AuditSuite) Test_SetEvents_InvalidEvent() {
err := s.grpcCli.Invoke("admin/log/set_events").
err := s.httpCli.Post("admin/log/set_events").
JsonRequestBody([]domain.SetAuditEvent{
{Event: entity.EventUserChanged, Enabled: true},
{Event: "новый#2", Enabled: false},
}).
Do(s.T().Context())
StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().Error(err)
status, isStatus := status.FromError(err)
s.Require().True(isStatus)
s.Require().Equal(codes.InvalidArgument, status.Code())
var httpErr httpcli.ErrorResponse
s.Require().ErrorAs(err, &httpErr)
s.Require().Equal(http.StatusBadRequest, httpErr.StatusCode)
}
func (s *AuditSuite) Test_All_Logs() {
request := domain.AuditPageRequest{
LimitOffestParams: domain.LimitOffestParams{
Limit: 3,
Offset: 5,
},
Limit: 3,
Offset: 5,
Order: &domain.OrderParams{
Field: "user_id",
Type: "desc",
@@ -194,11 +192,11 @@ func (s *AuditSuite) Test_All_Logs() {
}
var response *domain.AuditResponse
err := s.grpcCli.
Invoke("admin/log/all").
err := s.httpCli.
Post("admin/log/all").
JsonRequestBody(request).
JsonResponseBody(&response).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
s.Require().Len(response.Items, 3)
@@ -212,11 +210,11 @@ func (s *AuditSuite) Test_All_Logs() {
request.Limit = 10
request.Offset = 0
err = s.grpcCli.
Invoke("admin/log/all").
err = s.httpCli.
Post("admin/log/all").
JsonRequestBody(request).
JsonResponseBody(&response).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
s.Require().Len(response.Items, 6)
+57 -50
View File
@@ -18,18 +18,15 @@ import (
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/test/fake"
"github.com/txix-open/isp-kit/test/httpt"
"golang.org/x/sync/errgroup"
"github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/dbx"
"github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/http/httpcli"
"github.com/txix-open/isp-kit/json"
"github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/grpct"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func TestAuthTestSuite(t *testing.T) {
@@ -42,7 +39,7 @@ type AuthTestSuite struct {
test *test.Test
db *dbt.TestDb
grpcCli *client.Client
httpCli *httpcli.Client
oauthCli *httpcli.Client
oauthClientName string
}
@@ -81,11 +78,11 @@ func (s *AuthTestSuite) SetupTest() {
Config(s.T().Context(), remote, time.Minute)
s.Require().NoError(err)
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
s.grpcCli = apiCli
server, cli := httpt.TestServer(s.test, cfg.Handler)
s.httpCli = cli
testInstance.T().Cleanup(func() {
server.Shutdown()
server.Close()
mocksrv.Close()
})
}
@@ -99,13 +96,13 @@ func (s *AuthTestSuite) TestLoginHappyPath() {
})
response := domain.LoginResponse{}
err := s.grpcCli.Invoke("admin/auth/login").
err := s.httpCli.Post("admin/auth/login").
JsonRequestBody(domain.LoginRequest{
Email: "a@a.ru",
Password: "password",
}).
JsonResponseBody(&response).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
tokenInfo := SelectTokenEntityByToken(s.db, response.Token)
@@ -115,16 +112,18 @@ func (s *AuthTestSuite) TestLoginHappyPath() {
}
func (s *AuthTestSuite) TestLoginNotFound() {
err := s.grpcCli.Invoke("admin/auth/login").
err := s.httpCli.Post("admin/auth/login").
JsonRequestBody(domain.LoginRequest{
Email: "a1@a.ru",
Password: "password",
}).
Do(s.T().Context())
StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().Error(err)
st, ok := status.FromError(err)
s.Require().True(ok)
s.Require().Equal(codes.Unauthenticated, st.Code())
var httpErr httpcli.ErrorResponse
s.Require().ErrorAs(err, &httpErr)
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
}
@@ -138,16 +137,18 @@ func (s *AuthTestSuite) TestBlockedUser() {
Blocked: true,
})
err := s.grpcCli.Invoke("admin/auth/login").
err := s.httpCli.Post("admin/auth/login").
JsonRequestBody(domain.LoginRequest{
Email: "a@a.ru",
Password: "password",
}).
Do(s.T().Context())
StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().Error(err)
st, ok := status.FromError(err)
s.Require().True(ok)
s.Require().Equal(codes.Unauthenticated, st.Code())
var httpErr httpcli.ErrorResponse
s.Require().ErrorAs(err, &httpErr)
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
}
@@ -160,16 +161,18 @@ func (s *AuthTestSuite) TestLoginWrongPassword() {
Password: "password",
})
err := s.grpcCli.Invoke("admin/auth/login").
err := s.httpCli.Post("admin/auth/login").
JsonRequestBody(domain.LoginRequest{
Email: "a@a.ru",
Password: "WrongPassword",
}).
Do(s.T().Context())
StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().Error(err)
st, ok := status.FromError(err)
s.Require().True(ok)
s.Require().Equal(codes.Unauthenticated, st.Code())
var httpErr httpcli.ErrorResponse
s.Require().ErrorAs(err, &httpErr)
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
}
@@ -177,13 +180,13 @@ func (s *AuthTestSuite) TestLoginWrongPassword() {
func (s *AuthTestSuite) TestOauthLoginHappyPath() {
response := domain.LoginResponse{}
err := s.grpcCli.Invoke("admin/auth/login_with_oauth").
err := s.httpCli.Post("admin/auth/login_with_oauth").
JsonRequestBody(domain.LoginOauthRequest{
AuthCode: "code",
ClientName: s.oauthClientName,
}).
JsonResponseBody(&response).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
user := entity.User{}
s.db.Must().SelectRow(&user, "select id, email, full_name from users where oauth_user_id = $1", "oauthUser1")
@@ -199,17 +202,19 @@ func (s *AuthTestSuite) TestOauthLoginHappyPath() {
func (s *AuthTestSuite) TestOauthLogin_UnknownClient() {
response := domain.LoginResponse{}
err := s.grpcCli.Invoke("admin/auth/login_with_oauth").
err := s.httpCli.Post("admin/auth/login_with_oauth").
JsonRequestBody(domain.LoginOauthRequest{
AuthCode: "code",
ClientName: s.oauthClientName + fake.It[string](),
}).
JsonResponseBody(&response).
Do(s.T().Context())
StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().Error(err)
st, ok := status.FromError(err)
s.Require().True(ok)
s.Require().Equal(codes.Unauthenticated, st.Code())
var httpErr httpcli.ErrorResponse
s.Require().ErrorAs(err, &httpErr)
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
}
func (s *AuthTestSuite) Test_Logout_HappyPath() {
@@ -221,9 +226,9 @@ func (s *AuthTestSuite) Test_Logout_HappyPath() {
CreatedAt: time.Time{},
ExpiredAt: time.Time{},
})
err := s.grpcCli.Invoke("admin/auth/logout").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))).
Do(s.T().Context())
err := s.httpCli.Post("admin/auth/logout").
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))).
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
tokenInfo := SelectTokenEntityByToken(s.db, "token-841297641213")
@@ -233,18 +238,16 @@ func (s *AuthTestSuite) Test_Logout_HappyPath() {
}
func (s *AuthTestSuite) Test_Logout_NotFound() {
err := s.grpcCli.Invoke("admin/auth/logout").
AppendMetadata(domain.AdminAuthIdHeader, "0143218411981").
Do(s.T().Context())
err := s.httpCli.Post("admin/auth/logout").
Header(domain.AdminAuthIdHeader, "0143218411981").
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
time.Sleep(time.Second)
audit := repository.NewAudit(s.db)
auditList, err := audit.AllByRequest(s.T().Context(), domain.AuditPageRequest{
LimitOffestParams: domain.LimitOffestParams{
Limit: 10,
Offset: 0,
},
Limit: 10,
Offset: 0,
Order: &domain.OrderParams{
Field: "created_at",
Type: "desc",
@@ -266,9 +269,9 @@ func (s *AuthTestSuite) Test_Logout_AlreadyRevoke() {
CreatedAt: time.Time{},
ExpiredAt: time.Time{},
})
err := s.grpcCli.Invoke("admin/auth/logout").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))).
Do(s.T().Context())
err := s.httpCli.Post("admin/auth/logout").
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))).
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
tokenInfo := SelectTokenEntityByToken(s.db, "token-148623719462")
@@ -292,20 +295,24 @@ func (s *AuthTestSuite) TestBruteForceLogin() {
group.Go(func() error {
start := time.Now()
response := domain.LoginResponse{}
err := s.grpcCli.Invoke("admin/auth/login").
err := s.httpCli.Post("admin/auth/login").
JsonRequestBody(domain.LoginRequest{
Email: "a@a.ru",
Password: fmt.Sprintf("password %s", strconv.Itoa(index)),
}).
JsonResponseBody(&response).
Do(ctx)
StatusCodeToError().
DoWithoutResponse(ctx)
s.Require().Error(err)
switch status.Code(err) { // nolint:exhaustive
case codes.ResourceExhausted:
var httpErr httpcli.ErrorResponse
s.Require().ErrorAs(err, &httpErr)
switch httpErr.StatusCode { // nolint:exhaustive
case http.StatusTooManyRequests:
tooManyRequestsErrorCount.Add(1)
s.Require().True(time.Since(start) < time.Second)
case codes.Unauthenticated:
case http.StatusUnauthorized:
unauthorizedErrorCount.Add(1)
s.Require().True(time.Since(start) > time.Second)
default:
+9 -9
View File
@@ -9,10 +9,10 @@ import (
"github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/dbx"
"github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/http/httpcli"
"github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/grpct"
"github.com/txix-open/isp-kit/test/httpt"
)
func TestCustomizationTestSuite(t *testing.T) {
@@ -25,7 +25,7 @@ type CustomizationTestSuite struct {
test *test.Test
db *dbt.TestDb
grpcCli *client.Client
httpCli *httpcli.Client
}
func (s *CustomizationTestSuite) SetupTest() {
@@ -44,21 +44,21 @@ func (s *CustomizationTestSuite) SetupTest() {
Config(s.T().Context(), remote, time.Minute)
s.Require().NoError(err)
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
s.grpcCli = apiCli
server, cli := httpt.TestServer(s.test, cfg.Handler)
s.httpCli = cli
testInstance.T().Cleanup(func() {
server.Shutdown()
server.Close()
})
}
func (s *CustomizationTestSuite) TestGetDesign() {
response := conf.UIDesign{}
err := s.grpcCli.
Invoke("admin/user/get_design").
err := s.httpCli.
Post("admin/user/get_design").
JsonRequestBody(struct{}{}).
JsonResponseBody(&response).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
expected := conf.UIDesign{
Name: "test",
+7 -3
View File
@@ -42,9 +42,13 @@ func InsertRole(db *dbt.TestDb, role entity.Role) int64 {
}
q, args, err := query.New().
Insert("roles").
Columns("name", "permissions").
Values(role.Name, role.Permissions).
Suffix("ON CONFLICT (name) DO UPDATE SET name = EXCLUDED.name, permissions = EXCLUDED.permissions RETURNING id").
Columns("name", "permissions", "application_group").
Values(role.Name, role.Permissions, role.ApplicationGroup).
Suffix(`ON CONFLICT (name) DO UPDATE SET
name = EXCLUDED.name,
permissions = EXCLUDED.permissions,
application_group = EXCLUDED.application_group
RETURNING id`).
ToSql()
if err != nil {
panic(errors.WithMessagef(err, "insert role"))
+243
View File
@@ -0,0 +1,243 @@
// nolint: funlen
package tests_test
import (
"encoding/csv"
"net/http"
"testing"
"time"
"isp-admin-service/assembly"
"isp-admin-service/conf"
"isp-admin-service/domain"
"isp-admin-service/entity"
"isp-admin-service/repository"
"github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/dbx"
"github.com/txix-open/isp-kit/http/httpcli"
"github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/httpt"
)
func TestDownloadSuite(t *testing.T) {
t.Parallel()
suite.Run(t, &DownloadSuite{})
}
type DownloadSuite struct {
suite.Suite
test *test.Test
db *dbt.TestDb
httpCli *httpcli.Client
permissions entity.PermList
}
func (s *DownloadSuite) SetupTest() {
testInstance, _ := test.New(s.T())
s.test = testInstance
s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger()))
remote := conf.Remote{
Permissions: []conf.Permission{
{
Key: "data_download",
Name: "123",
},
},
}
cfg, err := assembly.NewLocator(testInstance.Logger(), nil, s.db).
Config(s.T().Context(), remote, time.Minute)
s.Require().NoError(err)
server, cli := httpt.TestServer(s.test, cfg.Handler)
s.httpCli = cli
s.permissions = entity.PermList{
"data_download",
}
testInstance.T().Cleanup(func() {
server.Close()
})
}
func (s *DownloadSuite) TestUsersHappyPath() {
id1 := InsertUser(s.db, entity.User{
FirstName: "Alice",
LastName: "Bob",
FullName: "Bob Alice",
Email: "alice@a.ru",
Password: "password",
})
roleId := InsertRole(s.db, entity.Role{Name: "admin", Permissions: s.permissions})
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(id1)})
resp, err := s.httpCli.Post("user/download").
JsonRequestBody(domain.UsersPageRequest{
Limit: 1000,
Offset: 0,
Order: &domain.OrderParams{
Field: "id",
Type: "desc",
},
}).
Do(s.T().Context())
s.Require().NoError(err)
defer resp.Raw.Body.Close()
s.Require().Equal(http.StatusOK, resp.StatusCode())
records, err := csv.NewReader(resp.Raw.Body).ReadAll()
s.Require().NoError(err)
s.Require().NotEmpty(records)
header := records[0]
col := make(map[string]int, len(header))
for i, name := range header {
col[name] = i
}
idIdx, ok := col["id"]
s.Require().True(ok)
emailIdx, ok := col["Email"]
s.Require().True(ok)
fullNameIdx, ok := col["Пользователь"]
s.Require().True(ok)
s.Require().Len(records, 4)
row := records[1]
s.Require().EqualValues("3", row[idIdx])
s.Require().EqualValues("alice@a.ru", row[emailIdx])
s.Require().EqualValues("Bob Alice", row[fullNameIdx])
}
func (s *DownloadSuite) TestSessionsHappyPath() {
timeNow := time.Now().UTC()
userId := InsertUser(s.db, entity.User{Email: "sess1@a.ru", FullName: "Bob Alice"})
roleId := InsertRole(s.db, entity.Role{Name: "admin", Permissions: s.permissions})
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(userId)})
InsertTokenEntity(s.db, entity.Token{
Token: "test_token_1",
UserId: userId,
Status: entity.TokenStatusAllowed,
ExpiredAt: timeNow.Add(1 * time.Hour),
CreatedAt: timeNow.Add(-1 * time.Hour),
UpdatedAt: timeNow,
})
InsertTokenEntity(s.db, entity.Token{
Token: "test_token_2",
UserId: userId,
Status: entity.TokenStatusRevoked,
ExpiredAt: timeNow.Add(1 * time.Hour),
CreatedAt: timeNow.Add(-2 * time.Hour),
UpdatedAt: timeNow,
})
InsertTokenEntity(s.db, entity.Token{
Token: "test_token_3",
UserId: userId,
Status: entity.TokenStatusExpired,
ExpiredAt: timeNow.Add(-1 * time.Hour),
CreatedAt: timeNow.Add(-3 * time.Hour),
UpdatedAt: timeNow,
})
resp, err := s.httpCli.Post("/session/download").
JsonRequestBody(domain.SessionPageRequest{
Limit: 1000,
Offset: 0,
Order: &domain.OrderParams{
Field: "user_id",
Type: "desc",
},
}).
Do(s.T().Context())
s.Require().NoError(err)
defer resp.Raw.Body.Close()
s.Require().Equal(http.StatusOK, resp.StatusCode())
records, err := csv.NewReader(resp.Raw.Body).ReadAll()
s.Require().NoError(err)
s.Require().NotEmpty(records)
header := records[0]
col := make(map[string]int, len(header))
for i, name := range header {
col[name] = i
}
userIdx, ok := col["Пользователь"]
s.Require().True(ok)
idIdx, ok := col["Идентификатор"]
s.Require().True(ok)
s.Require().Len(records, 4)
row := records[1]
s.Require().EqualValues("Bob Alice", row[userIdx])
s.Require().EqualValues("1", row[idIdx])
}
func (s *DownloadSuite) TestAuditHappyPath() {
timeNow := time.Now().UTC()
userId := InsertUser(s.db, entity.User{Email: "audit1@a.ru", FullName: "Bob Alice"})
roleId := InsertRole(s.db, entity.Role{Name: "admin", Permissions: s.permissions})
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(userId)})
auditRepo := repository.NewAudit(s.db)
_, err := auditRepo.Insert(s.T().Context(), entity.Audit{
Id: 1,
UserId: int(userId),
Message: "audit1@a.ru",
Event: "123456",
CreatedAt: timeNow,
})
s.Require().NoError(err)
resp, err := s.httpCli.Post("log/download").
JsonRequestBody(domain.AuditPageRequest{
Limit: 1000,
Offset: 0,
Order: &domain.OrderParams{
Field: "user_id",
Type: "desc",
},
}).
StatusCodeToError().
Do(s.T().Context())
s.Require().NoError(err)
records, err := csv.NewReader(resp.Raw.Body).ReadAll()
s.Require().NoError(err)
s.Require().NotEmpty(records)
header := records[0]
col := make(map[string]int, len(header))
for i, name := range header {
col[name] = i
}
idIdx, ok := col["Пользователь"]
s.Require().True(ok)
moveIdx, ok := col["Действие"]
s.Require().True(ok)
s.Require().Len(records, 2)
row := records[1]
s.Require().EqualValues("Bob Alice", row[idIdx])
s.Require().EqualValues("audit1@a.ru", row[moveIdx])
}
func (s *DownloadSuite) TestRolesHappyPath() {
resp, err := s.httpCli.Post("role/download").
StatusCodeToError().
Do(s.T().Context())
s.Require().NoError(err)
records, err := csv.NewReader(resp.Raw.Body).ReadAll()
s.Require().NoError(err)
s.Require().NotEmpty(records)
}
+2 -4
View File
@@ -49,10 +49,8 @@ func TestInactiveWorker(t *testing.T) {
require.True(user.Blocked)
list, err := repository.NewAudit(db).AllByRequest(t.Context(), domain.AuditPageRequest{
LimitOffestParams: domain.LimitOffestParams{
Limit: 10,
Offset: 0,
},
Limit: 10,
Offset: 0,
Order: &domain.OrderParams{
Field: "created_at",
Type: "desc",
+173
View File
@@ -0,0 +1,173 @@
package tests_test
import (
"net/http"
"strconv"
"testing"
"time"
"isp-admin-service/assembly"
"isp-admin-service/conf"
"isp-admin-service/domain"
"isp-admin-service/entity"
"github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/dbx"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/http/httpcli"
"github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/httpt"
)
func TestRoleTestSuite(t *testing.T) {
t.Parallel()
suite.Run(t, &RoleTestSuite{})
}
type RoleTestSuite struct {
suite.Suite
test *test.Test
db *dbt.TestDb
httpCli *httpcli.Client
adminId int64
}
func (s *RoleTestSuite) SetupTest() {
testInstance, _ := test.New(s.T())
s.test = testInstance
s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger()))
remote := conf.Remote{
ExpireSec: 0,
}
cfg, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), s.db).
Config(s.T().Context(), remote, time.Minute)
s.Require().NoError(err)
server, apiCli := httpt.TestServer(testInstance, cfg.Handler)
s.httpCli = apiCli
testInstance.T().Cleanup(func() {
server.Close()
})
roleId := InsertRole(s.db, entity.Role{
Name: "admin_test",
Permissions: []string{
"role_view",
"role_add",
"role_update",
},
})
s.adminId = InsertUser(s.db, entity.User{
Email: "admin@test.ru",
})
InsertUserRole(s.db, entity.UserRole{
UserId: int(s.adminId),
RoleId: int(roleId),
})
}
func (s *RoleTestSuite) TestAllRolesWithoutFilter() {
InsertRole(s.db, entity.Role{Name: "empty"})
InsertRole(s.db, entity.Role{Name: "groupA_1", ApplicationGroup: "groupA"})
InsertRole(s.db, entity.Role{Name: "groupA_2", ApplicationGroup: "groupA"})
InsertRole(s.db, entity.Role{Name: "groupB", ApplicationGroup: "groupB"})
roles := []domain.Role{}
_, err := s.request("admin/role/all", domain.RoleAllRequest{}, &roles)
s.Require().NoError(err)
groups := make(map[string]string, len(roles))
for _, role := range roles {
groups[role.Name] = role.ApplicationGroup
}
s.Require().Empty(groups["empty"])
s.Require().Equal("groupA", groups["groupA_1"])
s.Require().Equal("groupA", groups["groupA_2"])
s.Require().Equal("groupB", groups["groupB"])
}
func (s *RoleTestSuite) TestAllRolesInvalidArgument() {
roles := []domain.Role{}
statusCode, err := s.request("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("")}, &roles)
s.Require().Error(err)
s.Require().Equal(http.StatusBadRequest, statusCode)
s.Require().Empty(roles)
}
func (s *RoleTestSuite) TestAllRolesFilterByApplicationGroup() {
InsertRole(s.db, entity.Role{Name: "groupA", ApplicationGroup: "groupA"})
InsertRole(s.db, entity.Role{Name: "groupB", ApplicationGroup: "groupB"})
roles := []domain.Role{}
_, err := s.request("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("groupA")}, &roles)
s.Require().NoError(err)
s.Require().Len(roles, 1)
s.Require().Equal("groupA", roles[0].ApplicationGroup)
roles = []domain.Role{}
_, err = s.request("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("groupC")}, &roles)
s.Require().NoError(err)
s.Require().Empty(roles)
}
func (s *RoleTestSuite) TestCreateRoleApplicationGroup() {
role := domain.Role{}
_, err := s.request("admin/role/create", domain.CreateRoleRequest{
Name: "role_new",
ApplicationGroup: "group",
Permissions: []string{},
}, &role)
s.Require().NoError(err)
roleEmpty := domain.Role{}
_, err = s.request("admin/role/create", domain.CreateRoleRequest{
Name: "role_empty",
Permissions: []string{},
}, &roleEmpty)
s.Require().NoError(err)
s.Require().Equal("role_new", role.Name)
s.Require().Equal("group", role.ApplicationGroup)
s.Require().Equal("role_empty", roleEmpty.Name)
s.Require().Empty(roleEmpty.ApplicationGroup)
}
func (s *RoleTestSuite) TestUpdateRoleApplicationGroup() {
roleId := InsertRole(s.db, entity.Role{
Name: "role_old",
ApplicationGroup: "group_old",
})
role := domain.Role{}
_, err := s.request("admin/role/update", domain.UpdateRoleRequest{
Id: int(roleId),
Name: "role_new",
ApplicationGroup: "group_new",
Permissions: []string{},
}, &role)
s.Require().NoError(err)
s.Require().Equal("role_new", role.Name)
s.Require().Equal("group_new", role.ApplicationGroup)
}
func (s *RoleTestSuite) request(path string, req, resp any) (int, error) {
err := s.httpCli.Post(path).
JsonRequestBody(req).
JsonResponseBody(resp).
StatusCodeToError().
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(s.adminId))).
DoWithoutResponse(s.T().Context())
if err != nil {
return http.StatusBadRequest, errors.WithMessagef(err, "request %s", path)
}
return http.StatusOK, nil
}
+19 -20
View File
@@ -12,11 +12,10 @@ import (
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/dbx"
"github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/http/httpcli"
"github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/grpct"
"github.com/txix-open/isp-kit/test/httpt"
)
func TestSecureSuite(t *testing.T) {
@@ -30,7 +29,7 @@ type SecureSuite struct {
test *test.Test
require *require.Assertions
db *dbt.TestDb
grpcCli *client.Client
httpCli *httpcli.Client
}
func (s *SecureSuite) SetupTest() {
@@ -44,11 +43,11 @@ func (s *SecureSuite) SetupTest() {
Config(s.T().Context(), remote, time.Minute)
s.Require().NoError(err)
server, apiCli := grpct.TestServer(s.test, cfg.Handler)
server, apiCli := httpt.TestServer(s.test, cfg.Handler)
s.test.T().Cleanup(func() {
server.Shutdown()
server.Close()
})
s.grpcCli = apiCli
s.httpCli = apiCli
}
func (s *SecureSuite) Test_Authenticate_HappyPath() {
@@ -61,12 +60,12 @@ func (s *SecureSuite) Test_Authenticate_HappyPath() {
})
result := domain.SecureAuthResponse{}
err := s.grpcCli.Invoke("admin/secure/authenticate").
err := s.httpCli.Post("admin/secure/authenticate").
JsonRequestBody(domain.SecureAuthRequest{
Token: "happy_path",
}).
JsonResponseBody(&result).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.require.NoError(err)
s.require.Equal(domain.SecureAuthResponse{
Authenticated: true,
@@ -85,12 +84,12 @@ func (s *SecureSuite) Test_Authenticate_StatusRevoked() {
})
result := domain.SecureAuthResponse{}
err := s.grpcCli.Invoke("admin/secure/authenticate").
err := s.httpCli.Post("admin/secure/authenticate").
JsonRequestBody(domain.SecureAuthRequest{
Token: "revoked",
}).
JsonResponseBody(&result).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.require.NoError(err)
s.require.Equal(domain.SecureAuthResponse{
Authenticated: false,
@@ -109,12 +108,12 @@ func (s *SecureSuite) Test_Authenticate_Expired() {
})
result := domain.SecureAuthResponse{}
err := s.grpcCli.Invoke("admin/secure/authenticate").
err := s.httpCli.Post("admin/secure/authenticate").
JsonRequestBody(domain.SecureAuthRequest{
Token: "expired",
}).
JsonResponseBody(&result).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.require.NoError(err)
s.require.Equal(domain.SecureAuthResponse{
Authenticated: false,
@@ -125,12 +124,12 @@ func (s *SecureSuite) Test_Authenticate_Expired() {
func (s *SecureSuite) Test_Authenticate_NotFound() {
result := domain.SecureAuthResponse{}
err := s.grpcCli.Invoke("admin/secure/authenticate").
err := s.httpCli.Post("admin/secure/authenticate").
JsonRequestBody(domain.SecureAuthRequest{
Token: "not_found",
}).
JsonResponseBody(&result).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.require.NoError(err)
s.require.Equal(domain.SecureAuthResponse{
Authenticated: false,
@@ -165,35 +164,35 @@ func (s *SecureSuite) Test_Authorize_HappyPath() {
})
result := domain.SecureAuthzResponse{}
err := s.grpcCli.Invoke("admin/secure/authorize").
err := s.httpCli.Post("admin/secure/authorize").
JsonRequestBody(domain.SecureAuthzRequest{
AdminId: int(userId),
Permission: "perm1",
}).
JsonResponseBody(&result).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.require.NoError(err)
s.require.True(result.Authorized)
result = domain.SecureAuthzResponse{}
err = s.grpcCli.Invoke("admin/secure/authorize").
err = s.httpCli.Post("admin/secure/authorize").
JsonRequestBody(domain.SecureAuthzRequest{
AdminId: int(userId),
Permission: "perm2",
}).
JsonResponseBody(&result).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.require.NoError(err)
s.require.True(result.Authorized)
result = domain.SecureAuthzResponse{}
err = s.grpcCli.Invoke("admin/secure/authorize").
err = s.httpCli.Post("admin/secure/authorize").
JsonRequestBody(domain.SecureAuthzRequest{
AdminId: int(userId),
Permission: "perm3",
}).
JsonResponseBody(&result).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.require.NoError(err)
s.require.False(result.Authorized)
}
+24 -29
View File
@@ -14,11 +14,10 @@ import (
"github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/bgjobx"
"github.com/txix-open/isp-kit/dbx"
"github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/http/httpcli"
"github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/grpct"
"github.com/txix-open/isp-kit/test/httpt"
)
func TestSessionSuite(t *testing.T) {
@@ -32,7 +31,7 @@ type SessionSuite struct {
test *test.Test
db *dbt.TestDb
config assembly.Config
grpcCli *client.Client
httpCli *httpcli.Client
}
func (s *SessionSuite) SetupTest() {
@@ -77,11 +76,11 @@ func (s *SessionSuite) SetupTest() {
s.config = config
server, apiCli := grpct.TestServer(testInstance, s.config.Handler)
s.grpcCli = apiCli
server, cli := httpt.TestServer(s.test, config.Handler)
s.httpCli = cli
testInstance.T().Cleanup(func() {
server.Shutdown()
server.Close()
})
}
@@ -117,18 +116,16 @@ func (s *SessionSuite) Test_All_Session() {
// Дефолт сортировка, лимит и оффсет
request := domain.SessionPageRequest{
LimitOffestParams: domain.LimitOffestParams{
Limit: 5,
Offset: 1,
},
Limit: 5,
Offset: 1,
}
var response *domain.SessionResponse
err := s.grpcCli.
Invoke("admin/session/all").
err := s.httpCli.
Post("admin/session/all").
JsonRequestBody(request).
JsonResponseBody(&response).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
s.Require().Len(response.Items, 2)
@@ -144,11 +141,11 @@ func (s *SessionSuite) Test_All_Session() {
To: timeNow.Add(24 * time.Hour),
},
}
err = s.grpcCli.
Invoke("admin/session/all").
err = s.httpCli.
Post("admin/session/all").
JsonRequestBody(request).
JsonResponseBody(&response).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
s.Require().Len(response.Items, 2)
@@ -163,11 +160,11 @@ func (s *SessionSuite) Test_All_Session() {
Type: "asc",
}
err = s.grpcCli.
Invoke("admin/session/all").
err = s.httpCli.
Post("admin/session/all").
JsonRequestBody(request).
JsonResponseBody(&response).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
s.Require().Len(response.Items, 3)
@@ -183,11 +180,11 @@ func (s *SessionSuite) Test_All_Session() {
Status: []string{entity.TokenStatusExpired},
}
err = s.grpcCli.
Invoke("admin/session/all").
err = s.httpCli.
Post("admin/session/all").
JsonRequestBody(request).
JsonResponseBody(&response).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
s.Require().Len(response.Items, 1)
@@ -208,10 +205,8 @@ func (s *SessionSuite) Test_All_Session() {
}
request = domain.SessionPageRequest{
LimitOffestParams: domain.LimitOffestParams{
Limit: 5,
Offset: 0,
},
Limit: 5,
Offset: 0,
Order: &domain.OrderParams{
Field: "id",
Type: "desc",
@@ -220,11 +215,11 @@ func (s *SessionSuite) Test_All_Session() {
Id: new(2),
},
}
err = s.grpcCli.
Invoke("admin/session/all").
err = s.httpCli.
Post("admin/session/all").
JsonRequestBody(request).
JsonResponseBody(&response).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
s.Require().Len(response.Items, 5)
+14 -13
View File
@@ -4,23 +4,22 @@ import (
"isp-admin-service/assembly"
"isp-admin-service/conf"
"isp-admin-service/domain"
"net/http"
"net/url"
"testing"
"github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/http/httpcli"
"github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/fake"
"github.com/txix-open/isp-kit/test/grpct"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/txix-open/isp-kit/test/httpt"
)
type UiSettingsSuite struct {
suite.Suite
test *test.Test
apiCli *client.Client
apiCli *httpcli.Client
oauthClientSetting conf.OauthClientConfig
baseOauthUrl string
}
@@ -54,18 +53,18 @@ func (s *UiSettingsSuite) SetupTest() {
Config(s.T().Context(), remote, 0)
s.Require().NoError(err)
_, s.apiCli = grpct.TestServer(s.test, cfg.Handler)
_, s.apiCli = httpt.TestServer(s.test, cfg.Handler)
}
func (s *UiSettingsSuite) Test_HappyPath() {
var resp domain.UiOauthSetting
err := s.apiCli.Invoke("admin/ui_settings/oauth").
err := s.apiCli.Post("admin/ui_settings/oauth").
JsonRequestBody(domain.ClientNameRequest{
ClientName: s.oauthClientSetting.ClientName,
}).
JsonResponseBody(&resp).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
loginURL, err := url.Parse(resp.LoginUrl)
@@ -93,13 +92,15 @@ func (s *UiSettingsSuite) Test_HappyPath() {
}
func (s *UiSettingsSuite) Test_UnknownClient() {
err := s.apiCli.Invoke("admin/ui_settings/oauth").
err := s.apiCli.Post("admin/ui_settings/oauth").
JsonRequestBody(domain.ClientNameRequest{
ClientName: s.oauthClientSetting.ClientName + fake.It[string](),
}).
Do(s.T().Context())
StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().Error(err)
st, ok := status.FromError(err)
s.Require().True(ok)
s.Require().Equal(codes.Unauthenticated, st.Code())
var httpErr httpcli.ErrorResponse
s.Require().ErrorAs(err, &httpErr)
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
}
+107 -99
View File
@@ -2,11 +2,12 @@ package tests_test
import (
"context"
"encoding/json"
"net/http"
"strconv"
"testing"
"time"
"github.com/txix-open/isp-kit/grpc/apierrors"
"golang.org/x/crypto/bcrypt"
"isp-admin-service/assembly"
@@ -19,13 +20,10 @@ import (
"github.com/google/uuid"
"github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/dbx"
"github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/http/httpcli"
"github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/grpct"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/txix-open/isp-kit/test/httpt"
)
type tokenService interface {
@@ -42,7 +40,7 @@ type UserTestSuite struct {
test *test.Test
db *dbt.TestDb
grpcCli *client.Client
apiCli *httpcli.Client
httpCli *httpcli.Client
tokenService tokenService
}
@@ -60,11 +58,11 @@ func (s *UserTestSuite) SetupTest() {
Config(s.T().Context(), remote, time.Minute)
s.Require().NoError(err)
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
s.grpcCli = apiCli
server, apiCli := httpt.TestServer(testInstance, cfg.Handler)
s.apiCli = apiCli
testInstance.T().Cleanup(func() {
server.Shutdown()
server.Close()
})
tokenRep := repository.NewToken(s.db)
@@ -90,10 +88,10 @@ func (s *UserTestSuite) TestGetProfileHappyPath() {
})
response := domain.AdminUserShort{}
err := s.grpcCli.Invoke("admin/user/get_profile").
err := s.apiCli.Post("admin/user/get_profile").
JsonResponseBody(&response).
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
Do(s.T().Context())
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
expected := domain.AdminUserShort{
FirstName: "name",
@@ -117,13 +115,14 @@ func (s *UserTestSuite) TestGetProfileNotFound() {
Password: "password",
})
err := s.grpcCli.Invoke("admin/user/get_profile").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id+1))).
Do(s.T().Context())
err := s.apiCli.Post("admin/user/get_profile").
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id+1))).
StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().Error(err)
st, ok := status.FromError(err)
s.Require().True(ok)
s.Require().Equal(codes.NotFound, st.Code())
var httpErr httpcli.ErrorResponse
s.Require().ErrorAs(err, &httpErr)
s.Require().Equal(http.StatusNotFound, httpErr.StatusCode)
}
func (s *UserTestSuite) TestGetProfileOauth() {
@@ -145,11 +144,11 @@ func (s *UserTestSuite) TestGetProfileOauth() {
})
response := domain.AdminUserShort{}
err := s.grpcCli.
Invoke("admin/user/get_profile").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
err := s.apiCli.
Post("admin/user/get_profile").
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
JsonResponseBody(&response).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
expected := domain.AdminUserShort{
FirstName: "name",
@@ -184,12 +183,10 @@ func (s *UserTestSuite) TestGetUsers() {
email := "a1@"
response := domain.UsersResponse{}
err := s.grpcCli.Invoke("admin/user/get_users").
err := s.apiCli.Post("admin/user/get_users").
JsonRequestBody(domain.UsersPageRequest{
LimitOffestParams: domain.LimitOffestParams{
Limit: 5,
Offset: 1,
},
Limit: 5,
Offset: 1,
Order: &domain.OrderParams{
Field: "email",
Type: "asc",
@@ -200,7 +197,7 @@ func (s *UserTestSuite) TestGetUsers() {
},
}).
JsonResponseBody(&response).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
roles := []int{int(roleId1), int(roleId2)}
@@ -212,12 +209,10 @@ func (s *UserTestSuite) TestGetUsers() {
s.Require().EqualValues(roles, response.Items[1].Roles)
email = "test@mail.ru"
err = s.grpcCli.Invoke("admin/user/get_users").
err = s.apiCli.Post("admin/user/get_users").
JsonRequestBody(domain.UsersPageRequest{
LimitOffestParams: domain.LimitOffestParams{
Limit: 10,
Offset: 0,
},
Limit: 10,
Offset: 0,
Order: &domain.OrderParams{
Field: "id",
Type: "asc",
@@ -228,7 +223,7 @@ func (s *UserTestSuite) TestGetUsers() {
},
}).
JsonResponseBody(&response).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
s.Require().Empty(response.Items)
}
@@ -251,7 +246,10 @@ func (s *UserTestSuite) TestAllGetUsers() {
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId2), UserId: int(userId2)})
response := domain.UsersResponse{}
err := s.grpcCli.Invoke("admin/user/get_all_users").JsonResponseBody(&response).Do(s.T().Context())
err := s.apiCli.Post("admin/user/get_all_users").
JsonResponseBody(&response).
StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
s.Require().Len(response.Items, 7)
@@ -296,12 +294,10 @@ func (s *UserTestSuite) TestGetUsersFilterByLastActiveAt() {
})
response := domain.UsersResponse{}
err = s.grpcCli.Invoke("admin/user/get_users").
err = s.apiCli.Post("admin/user/get_users").
JsonRequestBody(domain.UsersPageRequest{
LimitOffestParams: domain.LimitOffestParams{
Limit: 5,
Offset: 0,
},
Limit: 5,
Offset: 0,
Order: &domain.OrderParams{
Field: "lastSessionCreatedAt",
Type: "desc",
@@ -314,7 +310,7 @@ func (s *UserTestSuite) TestGetUsersFilterByLastActiveAt() {
},
}).
JsonResponseBody(&response).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
s.Require().Len(response.Items, 2)
@@ -332,12 +328,10 @@ func (s *UserTestSuite) TestGetUsersSortByName() {
userIdAL := InsertUser(s.db, entity.User{Email: "a1@d.ru", FirstName: "А", LastName: "Л", FullName: "Л А"})
response := domain.UsersResponse{}
err := s.grpcCli.Invoke("admin/user/get_users").
err := s.apiCli.Post("admin/user/get_users").
JsonRequestBody(domain.UsersPageRequest{
LimitOffestParams: domain.LimitOffestParams{
Limit: 10,
Offset: 0,
},
Limit: 10,
Offset: 0,
Order: &domain.OrderParams{
Field: "userId",
Type: "asc",
@@ -347,7 +341,7 @@ func (s *UserTestSuite) TestGetUsersSortByName() {
},
}).
JsonResponseBody(&response).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
s.Require().Len(response.Items, 4)
@@ -364,9 +358,9 @@ func (s *UserTestSuite) TestCreateUserHappyPath() {
s.db.Must().SelectRow(&preCount, "select count(*) from users")
response := entity.User{}
err := s.grpcCli.
Invoke("admin/user/create_user").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
err := s.apiCli.
Post("admin/user/create_user").
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
JsonRequestBody(domain.CreateUserRequest{
FirstName: "name",
LastName: "surname",
@@ -374,7 +368,7 @@ func (s *UserTestSuite) TestCreateUserHappyPath() {
Password: "password",
}).
JsonResponseBody(&response).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
postCount := 0
@@ -392,9 +386,9 @@ func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() {
s.db.Must().SelectRow(&preCount, "select count(*) from users")
response := entity.User{}
err := s.grpcCli.
Invoke("admin/user/create_user").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
err := s.apiCli.
Post("admin/user/create_user").
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
JsonRequestBody(domain.CreateUserRequest{
FirstName: "name",
LastName: "surname",
@@ -402,7 +396,7 @@ func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() {
Password: "password",
}).
JsonResponseBody(&response).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
postCount := 0
@@ -415,20 +409,22 @@ func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() {
func (s *UserTestSuite) TestCreateUserAlreadyExist() {
id := InsertUser(s.db, entity.User{Email: "exists@a.ru"})
err := s.grpcCli.
Invoke("admin/user/create_user").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
err := s.apiCli.
Post("admin/user/create_user").
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
JsonRequestBody(domain.CreateUserRequest{
FirstName: "name",
LastName: "surname",
Email: "exists@a.ru",
Password: "password",
}).
Do(s.T().Context())
StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().Error(err)
st, ok := status.FromError(err)
s.Require().True(ok)
s.Require().Equal(codes.AlreadyExists, st.Code())
var httpErr httpcli.ErrorResponse
s.Require().ErrorAs(err, &httpErr)
s.Require().Equal(http.StatusConflict, httpErr.StatusCode)
}
func (s *AuthTestSuite) TestUpdateUserHappyPath() {
@@ -440,12 +436,11 @@ func (s *AuthTestSuite) TestUpdateUserHappyPath() {
Email: "update@a.ru",
}
response := domain.User{}
err := s.grpcCli.
Invoke("admin/user/update_user").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
err := s.httpCli.Post("admin/user/update_user").
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
JsonRequestBody(req).
JsonResponseBody(&response).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
expected := domain.UpdateUserRequest{
Id: response.Id,
@@ -467,12 +462,11 @@ func (s *AuthTestSuite) TestUpdateOauthUserHappyPath() {
Email: "oauth@a.ru",
}
response := domain.User{}
err := s.grpcCli.
Invoke("admin/user/update_user").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
err := s.httpCli.Post("admin/user/update_user").
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
JsonRequestBody(req).
JsonResponseBody(&response).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
expected := domain.UpdateUserRequest{
Id: response.Id,
@@ -495,15 +489,16 @@ func (s *AuthTestSuite) TestUpdateUserAlreadyExist() {
LastName: "surname",
Email: "a_exists@a.ru",
}
err := s.grpcCli.
Invoke("admin/user/update_user").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
err := s.httpCli.Post("admin/user/update_user").
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
JsonRequestBody(req).
Do(s.T().Context())
StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().Error(err)
st, ok := status.FromError(err)
s.Require().True(ok)
s.Require().Equal(codes.AlreadyExists, st.Code())
var httpErr httpcli.ErrorResponse
s.Require().ErrorAs(err, &httpErr)
s.Require().Equal(http.StatusConflict, httpErr.StatusCode)
}
func (s *AuthTestSuite) TestUpdateUserWithOauthAlreadyExist() {
@@ -518,15 +513,16 @@ func (s *AuthTestSuite) TestUpdateUserWithOauthAlreadyExist() {
LastName: "surname",
Email: "a_exists@a.ru",
}
err := s.grpcCli.
Invoke("admin/user/update_user").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
err := s.httpCli.Post("admin/user/update_user").
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
JsonRequestBody(req).
Do(s.T().Context())
StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().Error(err)
st, ok := status.FromError(err)
s.Require().True(ok)
s.Require().Equal(codes.AlreadyExists, st.Code())
var httpErr httpcli.ErrorResponse
s.Require().ErrorAs(err, &httpErr)
s.Require().Equal(http.StatusConflict, httpErr.StatusCode)
}
func (s *UserTestSuite) TestDeleteUsers() {
@@ -536,12 +532,12 @@ func (s *UserTestSuite) TestDeleteUsers() {
InsertUser(s.db, entity.User{Email: "a_del@c.ru"})
response := domain.DeleteResponse{}
err := s.grpcCli.
Invoke("admin/user/delete_user").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
err := s.apiCli.
Post("admin/user/delete_user").
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
JsonRequestBody(domain.IdentitiesRequest{Ids: []int64{3, 4}}).
JsonResponseBody(&response).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
s.Require().Equal(2, response.Deleted)
@@ -567,10 +563,11 @@ func (s *UserTestSuite) TestBlockUser() {
UpdatedAt: time.Now(),
})
err := s.grpcCli.Invoke("admin/user/block_user").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
err := s.apiCli.Post("admin/user/block_user").
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
StatusCodeToError().
JsonRequestBody(domain.IdRequest{UserId: int(id)}).
Do(s.T().Context())
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
user, err := repository.NewUser(s.db).GetUserById(s.T().Context(), id)
@@ -598,20 +595,31 @@ func (s *UserTestSuite) TestChangePasswordUser() {
// check for err when invalid data
invalidReq := domain.ChangePasswordRequest{OldPassword: "invalid", NewPassword: "new_password"}
err := s.grpcCli.Invoke("admin/user/change_password").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
err := s.apiCli.Post("admin/user/change_password").
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
JsonRequestBody(invalidReq).
Do(s.T().Context())
StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().Error(err)
err = apierrors.FromError(err)
s.Require().Contains(err.Error(), strconv.Itoa(domain.ErrCodeInvalidPassword))
var httpErr httpcli.ErrorResponse
s.Require().ErrorAs(err, &httpErr)
s.Require().Equal(http.StatusBadRequest, httpErr.StatusCode)
var body struct {
ErrorCode int `json:"errorCode"`
ErrorMessage string `json:"errorMessage"`
}
s.Require().NoError(json.Unmarshal(httpErr.Body, &body))
s.Require().Equal(domain.ErrCodeInvalidPassword, body.ErrorCode)
// change password
changePswReq := domain.ChangePasswordRequest{OldPassword: "password", NewPassword: "new_password"}
err = s.grpcCli.Invoke("admin/user/change_password").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
err = s.apiCli.Post("admin/user/change_password").
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
JsonRequestBody(changePswReq).
Do(s.T().Context())
StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().NoError(err)
+3
View File
@@ -13,6 +13,9 @@
<a href="https://pkg.go.dev/github.com/gabriel-vasile/mimetype">
<img alt="Go Reference" src="https://pkg.go.dev/badge/github.com/gabriel-vasile/mimetype.svg">
</a>
<a href="https://github.com/gabriel-vasile/mimetype/actions/workflows/go.yml">
<img alt="Tests" src="https://github.com/gabriel-vasile/mimetype/actions/workflows/go.yml/badge.svg">
</a>
<a href="https://codecov.io/gh/gabriel-vasile/mimetype">
<img alt="Code coverage" src="https://codecov.io/gh/gabriel-vasile/mimetype/graph/badge.svg">
</a>
+142 -29
View File
@@ -46,12 +46,14 @@ type cdf struct {
satSecs int32s // list of SAT sector ids; usually a sub-slice of raw input
satEntries int // number of valid SAT entries reachable through satSecs
firstSSAT int32
ssatSecs int32s // list of SSAT sector ids, precomputed from the firstSSAT chain
dirRaw []byte // directory stream bytes (entries are decoded on demand)
sst []byte // short-stream pool (root storage's stream)
sstBuilt bool // whether sst was already loaded (it is loaded lazily)
rootStreamFirst int32 // first sector of the root storage short-stream pool
rootStreamSize uint32 // size of the root storage short-stream pool
rootStorageUUID []byte
rootChild int32 // directory id of the root storage's child tree
rootStorageUUID [16]byte
}
// parse reads the entire on-disk structure required for type detection. It
@@ -81,35 +83,108 @@ func parse(raw []byte, c *cdf) bool {
masterSAT := int32s{b: raw[76 : 76+4*masterSATSize]}
c.buildSAT(masterSAT, firstMSAT, nMSAT)
c.buildSSAT()
c.dirRaw = c.readLong(firstDirSec, 0)
c.rootStreamFirst = -1
c.rootChild = -1
var d dirEntry
for i, n := 0, c.dirLen(); i < n; i++ {
c.dirAt(i, &d)
if d.typ != dirTypeRootStorage || d.streamFirst < 0 {
if d.typ != dirTypeRootStorage {
continue
}
c.rootStorageUUID = d.storageUUID[:]
copy(c.rootStorageUUID[:], d.storageUUID[:])
c.rootChild = d.child
// Record where the short-stream pool lives; it is loaded lazily by
// shortStream the first time a short stream is actually read.
c.rootStreamFirst = d.streamFirst
c.rootStreamSize = d.size
if d.streamFirst >= 0 {
c.rootStreamFirst = d.streamFirst
c.rootStreamSize = d.size
}
break
}
return true
}
// rootChildIter iterates over the directory entries that are direct children
// of the root storage, walking the red-black sibling tree hanging off the root
// entry's child pointer. Restricting detection to root-level entries matters:
// embedded OLE objects (e.g. an Excel sheet inside a Word document) carry
// their own SummaryInformation streams deeper in the hierarchy, and a flat
// directory scan can pick those up instead of the document's own.
// If the tree is unusable (no valid root child) iteration degrades to a flat
// scan of all entries so truncated or malformed files still get best-effort
// detection. The iterator lives entirely on the caller's stack: it allocates
// nothing and decodes each visited entry into its inline d field.
type rootChildIter struct {
c *cdf
d dirEntry // entry decoded by the latest successful next call
n int // total directory entries
i int // next index for the flat fallback scan
flat bool // no usable tree; scan all entries instead
visited int // entries visited so far; guards against cyclic trees
sp int // number of ids on stack
stack [64]int32
}
// rootChildren returns an iterator over the root storage's direct children.
// Usage: for it := c.rootChildren(); it.next(); { ... use it.d ... }
func (c *cdf) rootChildren() rootChildIter {
it := rootChildIter{c: c, n: c.dirLen()}
if c.rootChild >= 0 && int(c.rootChild) < it.n {
it.stack[0] = c.rootChild
it.sp = 1
} else {
it.flat = true
}
return it
}
// next advances to the next entry, decoding it into it.d. It reports false
// when iteration is done.
func (it *rootChildIter) next() bool {
if it.flat {
if it.i >= it.n {
return false
}
it.c.dirAt(it.i, &it.d)
it.i++
return true
}
for it.sp > 0 {
it.sp--
id := it.stack[it.sp]
if id < 0 || int(id) >= it.n {
continue
}
if it.visited++; it.visited > it.n {
return false // cyclic sibling pointers in a malformed directory
}
it.c.dirAt(int(id), &it.d)
// Push the siblings. A valid red-black tree of n entries is at most
// 2*log2(n) deep, so the fixed-size stack cannot overflow for any
// real directory; if a malformed tree overflows it, the excess
// branches are dropped and detection degrades gracefully.
for _, sib := range [2]int32{it.d.left, it.d.right} {
if sib >= 0 && it.sp < len(it.stack) {
it.stack[it.sp] = sib
it.sp++
}
}
return true
}
return false
}
func (c *cdf) detect() CDFType {
for _, name := range []string{"\x05SummaryInformation", "\x05DocumentSummaryInformation"} {
if t, ok := c.detectFromSummary(name); ok {
return t
}
}
var d dirEntry
for i, n := 0, c.dirLen(); i < n; i++ {
c.dirAt(i, &d)
if t, ok := lookupSection(d.nameBytes(), d.typ); ok {
for it := c.rootChildren(); it.next(); {
if t, ok := lookupSection(it.d.nameBytes(), it.d.typ); ok {
return t
}
}
@@ -120,7 +195,7 @@ func (c *cdf) detect() CDFType {
// derive a CDFType from the root-storage CLSID, the property NameOfApplication,
// and finally the names of sibling user streams.
func (c *cdf) detectFromSummary(streamName string) (CDFType, bool) {
if c.rootStorageUUID != nil && bytes.Equal(c.rootStorageUUID, msiCLSID) {
if bytes.Equal(c.rootStorageUUID[:], msiCLSID) {
return CDFTypeInstaller, true
}
raw, ok := c.userStream(streamName)
@@ -132,13 +207,11 @@ func (c *cdf) detectFromSummary(streamName string) (CDFType, bool) {
return t, true
}
}
for i, n := 0, c.dirLen(); i < n; i++ {
var d dirEntry
c.dirAt(i, &d)
if d.nameLen == 0 {
for it := c.rootChildren(); it.next(); {
if it.d.nameLen == 0 {
continue
}
if t, ok := lookupSubstring(d.nameBytes(), name2type); ok {
if t, ok := lookupSubstring(it.d.nameBytes(), name2type); ok {
return t, true
}
}
@@ -164,6 +237,9 @@ type dirEntry struct {
name [32]byte
nameLen uint8
typ uint8
left int32 // left sibling directory id
right int32 // right sibling directory id
child int32 // first child directory id (for storages)
streamFirst int32
size uint32
storageUUID [16]byte
@@ -172,23 +248,56 @@ type dirEntry struct {
// nameBytes returns the decoded ASCII name without copying.
func (d *dirEntry) nameBytes() []byte { return d.name[:d.nameLen] }
func (c *cdf) ssatAt(i int32) int32 {
// buildSSAT records the list of SSAT sector ids by walking the firstSSAT chain
// through the SAT once. The SSAT contents are not materialized; ssatAt computes
// the requested entry directly from c.data via ssatSecs, mirroring satSecs/satAt.
// The walk is bounded by the number of sectors in the file so a cyclic SAT
// (a self-looping sector) cannot spin forever.
func (c *cdf) buildSSAT() {
maxIDs := len(c.data)/c.secSize + 1
buf := make([]byte, 0, 4*8)
var tmp [4]byte
for sid := c.firstSSAT; sid >= 0; {
if int(sid) >= c.satLen() {
break // SAT is truncated; stop collecting
}
buf, ok := c.sector(sid)
if !ok {
if _, ok := c.sector(sid); !ok {
break
}
lbuf := int32(len(buf) / 4) //nolint:gosec // anything divided by 4 fits int32
if i < lbuf {
return int32(binary.LittleEndian.Uint32(buf[4*i:])) //nolint:gosec // intentional two's-complement reinterpretation of a sector id
binary.LittleEndian.PutUint32(tmp[:], uint32(sid)) //nolint:gosec // reinterpret sector id
buf = append(buf, tmp[:]...)
if len(buf)/4 > maxIDs {
break // cyclic SAT chain; stop allocating
}
i -= lbuf
sid = c.satAt(sid)
}
return -1
c.ssatSecs = int32s{b: buf}
}
// ssatAt returns the i-th SSAT entry (a short-sector id) by indexing directly
// into the precomputed ssatSecs, the same way satAt indexes satSecs. It returns
// -1 when i is past the end of the SSAT or the backing sector is truncated.
func (c *cdf) ssatAt(i int32) int32 {
if i < 0 {
return -1
}
perSec := int32(c.secSize / 4) //nolint:gosec // secSize is a small power of two
secIdx := int(i / perSec)
if secIdx >= c.ssatSecs.len() {
return -1
}
sid := c.ssatSecs.at(secIdx)
buf, ok := c.sector(sid)
if !ok {
return -1
}
entryIdx := i % perSec
//nolint:gosec // anything divided by 4 fits int32
if entryIdx >= int32(len(buf)/4) {
return -1 // sector truncated short of this entry
}
//nolint:gosec // intentional two's-complement reinterpretation of a sector id
return int32(binary.LittleEndian.Uint32(buf[4*entryIdx:]))
}
// shortStream returns the root storage short-stream pool, loading it on first
@@ -435,6 +544,9 @@ func (c *cdf) readShort(sid int32, length uint32) []byte {
}
off := int(off64)
out = append(out, sst[off:off+c.shortSecSize]...)
if length > 0 && int64(len(out)) >= int64(length) {
break // read enough to satisfy the stream's declared length
}
if len(out) >= len(sst) {
break // chain longer than the pool: cyclic SSAT, stop
}
@@ -476,18 +588,19 @@ func (c *cdf) dirAt(i int, out *dirEntry) {
}
out.nameLen = k
out.typ = raw[66]
out.left = readSecID(raw[68:72])
out.right = readSecID(raw[72:76])
out.child = readSecID(raw[76:80])
out.streamFirst = readSecID(raw[116:120])
out.size = binary.LittleEndian.Uint32(raw[120:])
copy(out.storageUUID[:], raw[80:96])
}
// userStream finds a user stream by name and returns its bytes.
// userStream finds a root-level user stream by name and returns its bytes.
func (c *cdf) userStream(name string) ([]byte, bool) {
var d dirEntry
for i, n := 0, c.dirLen(); i < n; i++ {
c.dirAt(i, &d)
if d.typ == dirTypeUserStream && string(d.nameBytes()) == name {
buf := c.readChain(d.streamFirst, d.size)
for it := c.rootChildren(); it.next(); {
if it.d.typ == dirTypeUserStream && string(it.d.nameBytes()) == name {
buf := c.readChain(it.d.streamFirst, it.d.size)
if buf == nil {
return nil, false
}
+15 -12
View File
@@ -50,7 +50,7 @@ func M3U(raw []byte, _ uint32) bool {
// AAC matches an Advanced Audio Coding file.
func AAC(raw []byte, _ uint32) bool {
return len(raw) > 1 && ((raw[0] == 0xFF && raw[1] == 0xF1) || (raw[0] == 0xFF && raw[1] == 0xF9))
return len(raw) > 1 && raw[0] == 0xFF && (raw[1] == 0xF1 || raw[1] == 0xF9)
}
// MP3 matches a .mp3 file.
@@ -128,27 +128,30 @@ func id3v2(raw []byte) bool {
}
size := uint32(raw[6])<<21 | uint32(raw[7])<<14 | uint32(raw[8])<<7 | uint32(raw[9])
// Disallow too big frames, let's say 10MB.
return size > 0 && size < 10*1024*1024
// The synchsafe integer is already bounded to 28 bits (~256MB). A 10MB
// cap rejected legitimate files with large ID3v2 album art. #839
return size > 0
}
// iff checks for an Interchange File Format layout: 4-byte container tag,
// 4-byte size, 4-byte format tag.
func iff(raw []byte, container, format []byte) bool {
return len(raw) > 12 &&
bytes.Equal(raw[:4], container) &&
bytes.Equal(raw[8:12], format)
}
// Wav matches a Waveform Audio File Format file.
func Wav(raw []byte, limit uint32) bool {
return len(raw) > 12 &&
bytes.Equal(raw[:4], []byte("RIFF")) &&
bytes.Equal(raw[8:12], []byte{0x57, 0x41, 0x56, 0x45})
return iff(raw, []byte("RIFF"), []byte("WAVE"))
}
// Aiff matches Audio Interchange File Format file.
func Aiff(raw []byte, limit uint32) bool {
return len(raw) > 12 &&
bytes.Equal(raw[:4], []byte{0x46, 0x4F, 0x52, 0x4D}) &&
bytes.Equal(raw[8:12], []byte{0x41, 0x49, 0x46, 0x46})
return iff(raw, []byte("FORM"), []byte("AIFF"))
}
// Qcp matches a Qualcomm Pure Voice file.
func Qcp(raw []byte, limit uint32) bool {
return len(raw) > 12 &&
bytes.Equal(raw[:4], []byte("RIFF")) &&
bytes.Equal(raw[8:12], []byte("QLCM"))
return iff(raw, []byte("RIFF"), []byte("QLCM"))
}
+9 -16
View File
@@ -121,29 +121,22 @@ func Dbf(raw []byte, limit uint32) bool {
return slices.Contains(dbfTypes, raw[0])
}
// ElfObj matches an object file.
func ElfObj(raw []byte, limit uint32) bool {
return len(raw) > 17 && ((raw[16] == 0x01 && raw[17] == 0x00) ||
(raw[16] == 0x00 && raw[17] == 0x01))
func elfType(raw []byte, t byte) bool {
return len(raw) > 17 &&
((raw[16] == t && raw[17] == 0x00) || (raw[16] == 0x00 && raw[17] == t))
}
// ElfObj matches an object file.
func ElfObj(raw []byte, limit uint32) bool { return elfType(raw, 0x01) }
// ElfExe matches an executable file.
func ElfExe(raw []byte, limit uint32) bool {
return len(raw) > 17 && ((raw[16] == 0x02 && raw[17] == 0x00) ||
(raw[16] == 0x00 && raw[17] == 0x02))
}
func ElfExe(raw []byte, limit uint32) bool { return elfType(raw, 0x02) }
// ElfLib matches a shared library file.
func ElfLib(raw []byte, limit uint32) bool {
return len(raw) > 17 && ((raw[16] == 0x03 && raw[17] == 0x00) ||
(raw[16] == 0x00 && raw[17] == 0x03))
}
func ElfLib(raw []byte, limit uint32) bool { return elfType(raw, 0x03) }
// ElfDump matches a core dump file.
func ElfDump(raw []byte, limit uint32) bool {
return len(raw) > 17 && ((raw[16] == 0x04 && raw[17] == 0x00) ||
(raw[16] == 0x00 && raw[17] == 0x04))
}
func ElfDump(raw []byte, limit uint32) bool { return elfType(raw, 0x04) }
// Dcm matches a DICOM medical format file.
func Dcm(raw []byte, limit uint32) bool {
+1 -3
View File
@@ -178,9 +178,7 @@ func jpeg2k(raw []byte, sig []byte) bool {
// Webp matches a WebP file.
func Webp(raw []byte, _ uint32) bool {
return len(raw) > 12 &&
bytes.Equal(raw[0:4], []byte("RIFF")) &&
bytes.Equal(raw[8:12], []byte{0x57, 0x45, 0x42, 0x50})
return iff(raw, []byte("RIFF"), []byte("WEBP"))
}
// Dwg matches a CAD drawing file.
+1 -13
View File
@@ -101,25 +101,13 @@ func markup(b scan.Bytes, sigs ...[]byte) bool {
return false
}
func markupCheck(sig, raw []byte) bool {
if len(raw) < len(sig)+1 {
if !ciCheck(sig, raw) {
return false
}
// perform case insensitive check
for i, b := range sig {
db := raw[i]
if 'A' <= b && b <= 'Z' {
db &= 0xDF
}
if b != db {
return false
}
}
// Next byte must be space or right angle bracket.
if db := raw[len(sig)]; !scan.ByteIsWS(db) && db != '>' {
return false
}
return true
}
+31 -59
View File
@@ -46,26 +46,16 @@ func Ole(raw []byte, limit uint32) bool {
return bytes.HasPrefix(raw, []byte{0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1})
}
// Doc matches a Microsoft Word 97-2003 file.
// See: https://github.com/decalage2/oletools/blob/412ee36ae45e70f42123e835871bac956d958461/oletools/common/clsid.py
func Doc(raw []byte, _ uint32) bool {
// cdfOrClsid checks if the raw input is detected as the given CDF type, and if
// the CDF parser returns a generic result, falls back to matching root storage CLSIDs.
func cdfOrClsid(raw []byte, want cdf.CDFType, clsids ...[]byte) bool {
fromParsing := cdf.Detect(raw)
if fromParsing == cdf.CDFTypeDoc {
if fromParsing == want {
return true
}
if fromParsing != cdf.CDFTypeGeneric {
return false
}
// Fallback for inputs where the CDF directory is past the read limit: match
// the root storage CLSID, which often lies within the first sectors.
clsids := [][]byte{
// Microsoft Word 97-2003 Document (Word.Document.8)
{0x06, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
// Microsoft Word 6.0-7.0 Document (Word.Document.6)
{0x00, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
// Microsoft Word Picture (Word.Picture.8)
{0x07, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
}
for _, clsid := range clsids {
if matchOleClsid(raw, clsid) {
return true
@@ -74,25 +64,27 @@ func Doc(raw []byte, _ uint32) bool {
return false
}
// Doc matches a Microsoft Word 97-2003 file.
// See: https://github.com/decalage2/oletools/blob/412ee36ae45e70f42123e835871bac956d958461/oletools/common/clsid.py
func Doc(raw []byte, _ uint32) bool {
return cdfOrClsid(raw, cdf.CDFTypeDoc,
// Microsoft Word 97-2003 Document (Word.Document.8)
[]byte{0x06, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
// Microsoft Word 6.0-7.0 Document (Word.Document.6)
[]byte{0x00, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
// Microsoft Word Picture (Word.Picture.8)
[]byte{0x07, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
)
}
// Ppt matches a Microsoft PowerPoint 97-2003 file or a PowerPoint 95 presentation.
func Ppt(raw []byte, limit uint32) bool {
fromParsing := cdf.Detect(raw)
if fromParsing == cdf.CDFTypePpt {
return true
}
if fromParsing != cdf.CDFTypeGeneric {
return false
}
// Fallback for inputs where the CDF directory is past the read limit.
// Root CLSID test is the safest way to identify the OLE, however, the format
// often places the root CLSID at the end of the file.
if matchOleClsid(raw, []byte{
0x10, 0x8d, 0x81, 0x64, 0x9b, 0x4f, 0xcf, 0x11,
0x86, 0xea, 0x00, 0xaa, 0x00, 0xb9, 0x29, 0xe8,
}) || matchOleClsid(raw, []byte{
0x70, 0xae, 0x7b, 0xea, 0x3b, 0xfb, 0xcd, 0x11,
0xa9, 0x03, 0x00, 0xaa, 0x00, 0x51, 0x0e, 0xa3,
}) {
if cdfOrClsid(raw, cdf.CDFTypePpt,
[]byte{0x10, 0x8d, 0x81, 0x64, 0x9b, 0x4f, 0xcf, 0x11,
0x86, 0xea, 0x00, 0xaa, 0x00, 0xb9, 0x29, 0xe8},
[]byte{0x70, 0xae, 0x7b, 0xea, 0x3b, 0xfb, 0xcd, 0x11,
0xa9, 0x03, 0x00, 0xaa, 0x00, 0x51, 0x0e, 0xa3},
) {
return true
}
@@ -117,21 +109,10 @@ func Ppt(raw []byte, limit uint32) bool {
// Xls matches a Microsoft Excel 97-2003 file.
func Xls(raw []byte, limit uint32) bool {
fromParsing := cdf.Detect(raw)
if fromParsing == cdf.CDFTypeXls {
return true
}
if fromParsing != cdf.CDFTypeGeneric {
return false
}
// Fallback for inputs where the CDF directory is past the read limit.
// Root CLSID test is the safest way to identify the OLE, however, the format
// often places the root CLSID at the end of the file.
if matchOleClsid(raw, []byte{
0x10, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
}) || matchOleClsid(raw, []byte{
0x20, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
}) {
if cdfOrClsid(raw, cdf.CDFTypeXls,
[]byte{0x10, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00},
[]byte{0x20, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00},
) {
return true
}
@@ -168,19 +149,10 @@ func Pub(raw []byte, limit uint32) bool {
// Msg matches a Microsoft Outlook email file.
func Msg(raw []byte, limit uint32) bool {
fromParsing := cdf.Detect(raw)
if fromParsing == cdf.CDFTypeMsg {
return true
}
if fromParsing != cdf.CDFTypeGeneric {
return false
}
// Fallback for inputs where the CDF directory does not carry the streams the
// parser keys on: match the root storage CLSID instead.
return matchOleClsid(raw, []byte{
0x0B, 0x0D, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46,
})
return cdfOrClsid(raw, cdf.CDFTypeMsg,
[]byte{0x0B, 0x0D, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
)
}
// Msi matches a Microsoft Windows Installer file.
+3
View File
@@ -15,6 +15,9 @@ targets:
- name: github
tagPrefix: otel/otlp/v
tagOnly: true
- name: github
tagPrefix: cron/v
tagOnly: true
- name: github
tagPrefix: echo/v
tagOnly: true
+35
View File
@@ -1,5 +1,40 @@
# Changelog
## 0.50.0
### Breaking Changes 🛠
- adds NoopClient implementation. The SDK now returns a non-nil noop client and handles the previous nil checks with checking for a disabled client. Code paths that were using nil checks now need to check for `client.IsEnabled`. by @giortzisg in [#1365](https://github.com/getsentry/sentry-go/pull/1365)
### New Features ✨
#### Crons
- Add `sentry.WithMonitor` and `Hub.WithMonitor` to wrap a job in cron check-ins and create or update the monitor from code. by @wedamija in [#1443](https://github.com/getsentry/sentry-go/pull/1443)
- Add `sentrycron.AddFunc` to report robfig/cron jobs to Sentry Crons, using the job's spec as the monitor schedule. by @wedamija in [#1443](https://github.com/getsentry/sentry-go/pull/1443)
- Docs: https://github.com/getsentry/sentry-docs/pull/19778 by @wedamija in [#1443](https://github.com/getsentry/sentry-go/pull/1443)
### Bug Fixes 🐛
- (dsn) Build envelope URL without re-parsing by @giortzisg in [#1436](https://github.com/getsentry/sentry-go/pull/1436)
- (httpclient) Decouple span creation from trace propagation by @giortzisg in [#1421](https://github.com/getsentry/sentry-go/pull/1421)
- (slog) Stop replaceAttrs from mutating the handler's grouped attrs by @breken-ai in [#1439](https://github.com/getsentry/sentry-go/pull/1439)
- (zerolog) Unescape JSON string values before sending to Sentry by @breken-ai in [#1440](https://github.com/getsentry/sentry-go/pull/1440)
- Guard concurrent flushes by @giortzisg in [#1449](https://github.com/getsentry/sentry-go/pull/1449)
- Keep http.Hijacker when wrapping a response writer by @knQzx in [#1387](https://github.com/getsentry/sentry-go/pull/1387)
### Internal Changes 🔧
#### Deps
- Bump getsentry/craft from 2.30.1 to 2.31.2 by @dependabot in [#1441](https://github.com/getsentry/sentry-go/pull/1441)
- Bump getsentry/github-workflows/validate-pr from 4013fc6e1aeb1be1f9d3b4d232624f0ec1afa613 to 36c729264d2edc29ebae61950c50e1e9f043ad7e by @dependabot in [#1442](https://github.com/getsentry/sentry-go/pull/1442)
- Bump go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp from 1.43.0 to 1.45.0 in /otel/otlp by @dependabot in [#1430](https://github.com/getsentry/sentry-go/pull/1430)
- Bump go.opentelemetry.io/otel/sdk from 1.44.0 to 1.45.0 by @dependabot in [#1431](https://github.com/getsentry/sentry-go/pull/1431)
- Bump google.golang.org/grpc from 1.83.1 to 1.83.2 by @dependabot in [#1422](https://github.com/getsentry/sentry-go/pull/1422)
- Bump getsentry/craft from 2.27.2 to 2.30.1 by @dependabot in [#1411](https://github.com/getsentry/sentry-go/pull/1411)
- Bump google.golang.org/grpc from 1.82.1 to 1.83.1 by @dependabot in [#1413](https://github.com/getsentry/sentry-go/pull/1413)
## 0.49.0
### Breaking Changes 🛠
+6 -4
View File
@@ -305,6 +305,8 @@ func (t Type) String() string {
return "invalid"
}
const arrayType = "array"
// mapTypesToStr is a map from attribute.Type to the primitive types the server understands.
// https://develop.sentry.dev/sdk/foundations/data-model/attributes/#primitive-types
var mapTypesToStr = map[Type]string{
@@ -313,9 +315,9 @@ var mapTypesToStr = map[Type]string{
INT64: "integer",
FLOAT64: "double",
STRING: "string",
BOOLSLICE: "array",
INT64SLICE: "array",
FLOAT64SLICE: "array",
STRINGSLICE: "array",
BOOLSLICE: arrayType,
INT64SLICE: arrayType,
FLOAT64SLICE: arrayType,
STRINGSLICE: arrayType,
UINT64: "integer", // wire format: same "integer" type
}
+85 -9
View File
@@ -133,8 +133,8 @@ type ClientOptions struct {
// The DSN to use. If the DSN is not set, the client is effectively
// disabled.
Dsn string
// In debug mode, the debug information is printed to stdout to help you
// understand what sentry is doing.
// In debug mode, diagnostic information is written to DebugWriter, which
// defaults to stderr.
Debug bool
// Configures whether SDK should generate and attach stacktraces to pure
// capture message calls.
@@ -298,6 +298,7 @@ type ClientOptions struct {
// instances. It must be created with NewClient.
type Client struct {
mu sync.RWMutex
disabled bool
options ClientOptions
dsn *protocol.Dsn
eventProcessors []EventProcessor
@@ -450,6 +451,45 @@ func NewClient(options ClientOptions) (*Client, error) {
return &client, nil
}
var noopClient = &Client{
disabled: true,
options: ClientOptions{
DisableTelemetryBuffer: true,
MaxErrorDepth: maxErrorDepth,
MaxSpans: defaultMaxSpans,
TraceIgnoreStatusCodes: [][]int{{404}},
},
sdkIdentifier: sdkIdentifier,
sdkVersion: SDKVersion,
Transport: new(noopTransport),
reportRecorder: report.NoopRecorder(),
reportProvider: report.NoopProvider(),
}
// NewNoopClient returns the shared client that safely discards telemetry.
// Its mutating methods have no effect.
func NewNoopClient() *Client {
return noopClient
}
// IsEnabled reports whether the client processes captured telemetry.
//
// It returns false for a nil receiver and for clients returned by
// NewNoopClient. A client can be enabled while using a transport that discards
// telemetry, such as a client configured with an empty DSN.
func (client *Client) IsEnabled() bool {
return client != nil && !client.disabled
}
// normalizeClient returns client, or the shared no-op client when client is
// nil.
func normalizeClient(client *Client) *Client {
if client == nil {
return noopClient
}
return client
}
func (client *Client) setupTransport() {
opts := client.options
transport := opts.Transport
@@ -555,6 +595,9 @@ func (client *Client) setupIntegrations() {
// client is shared among multiple hubs, one per goroutine, such that adding an
// event processor to the client affects all hubs that share the client.
func (client *Client) AddEventProcessor(processor EventProcessor) {
if !client.IsEnabled() {
return
}
client.eventProcessors = append(client.eventProcessors, processor)
}
@@ -563,6 +606,9 @@ func (client *Client) AddEventProcessor(processor EventProcessor) {
//
// This is intended for integrations such as OpenTelemetry.
func (client *Client) SetExternalContextTraceResolver(resolver func(ctx context.Context) (TraceID, SpanID, bool)) {
if !client.IsEnabled() {
return
}
client.mu.Lock()
defer client.mu.Unlock()
@@ -596,7 +642,7 @@ func (client *Client) Options() ClientOptions {
// GetDataCollection returns a copy of the resolved data collection
// configuration used by the client.
func (client *Client) GetDataCollection() DataCollection {
if client == nil || client.options.DataCollection == nil {
if !client.IsEnabled() || client.options.DataCollection == nil {
return DataCollection{}
}
return *cloneDataCollection(client.options.DataCollection)
@@ -604,22 +650,32 @@ func (client *Client) GetDataCollection() DataCollection {
// CaptureMessage captures an arbitrary message.
func (client *Client) CaptureMessage(message string, hint *EventHint, scope EventModifier) *EventID {
if !client.IsEnabled() {
return nil
}
event := client.EventFromMessage(message, LevelInfo)
return client.CaptureEvent(event, hint, scope)
}
// CaptureException captures an error.
func (client *Client) CaptureException(exception error, hint *EventHint, scope EventModifier) *EventID {
if !client.IsEnabled() {
return nil
}
event := client.EventFromException(exception, LevelError)
return client.CaptureEvent(event, hint, scope)
}
// CaptureCheckIn captures a check in.
func (client *Client) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig, scope EventModifier) *EventID {
if !client.IsEnabled() {
return nil
}
event := client.EventFromCheckIn(checkIn, monitorConfig)
if event != nil && event.CheckIn != nil {
client.CaptureEvent(event, nil, scope)
return &event.CheckIn.ID
if client.CaptureEvent(event, nil, scope) != nil {
return &event.CheckIn.ID
}
}
return nil
}
@@ -630,6 +686,9 @@ func (client *Client) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorCon
// the utility methods like CaptureException. The return value is the
// event ID. In case Sentry is disabled or event was dropped, the return value will be nil.
func (client *Client) CaptureEvent(event *Event, hint *EventHint, scope EventModifier) *EventID {
if !client.IsEnabled() {
return nil
}
return client.processEvent(event, hint, scope)
}
@@ -727,6 +786,9 @@ func (client *Client) RecoverWithContext(
if err == nil {
return nil
}
if !client.IsEnabled() {
return nil
}
if ctx != nil {
if hint == nil {
@@ -751,7 +813,8 @@ func (client *Client) RecoverWithContext(
// Flush waits until the underlying Transport sends any buffered events to the
// Sentry server, blocking for at most the given timeout. It returns false if
// the timeout was reached. In that case, some events may not have been sent.
// the client is disabled or the timeout was reached. In the latter case, some
// events may not have been sent.
//
// Flush should be called before terminating the program to avoid
// unintentionally dropping events.
@@ -761,6 +824,9 @@ func (client *Client) RecoverWithContext(
// the network synchronously, configure it to use the HTTPSyncTransport in the
// call to Init.
func (client *Client) Flush(timeout time.Duration) bool {
if !client.IsEnabled() {
return false
}
if client.batchLogger != nil || client.batchMeter != nil || client.telemetryProcessor != nil {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
@@ -770,9 +836,10 @@ func (client *Client) Flush(timeout time.Duration) bool {
}
// FlushWithContext waits until the underlying Transport sends any buffered events
// to the Sentry server, blocking for at most the duration specified by the context.
// It returns false if the context is canceled before the events are sent. In such a case,
// some events may not be delivered.
// to the Sentry server, blocking for at most the duration specified by the
// context. It returns false if the client is disabled or the context is
// canceled before the events are sent. In the latter case, some events may not
// be delivered.
//
// FlushWithContext should be called before terminating the program to ensure no
// events are unintentionally dropped.
@@ -782,6 +849,9 @@ func (client *Client) Flush(timeout time.Duration) bool {
// configure the SDK to use HTTPSyncTransport during initialization with Init.
func (client *Client) FlushWithContext(ctx context.Context) bool {
if !client.IsEnabled() {
return false
}
if client.batchLogger != nil {
client.batchLogger.Flush(ctx.Done())
}
@@ -799,6 +869,9 @@ func (client *Client) FlushWithContext(ctx context.Context) bool {
// Close should be called after Flush and before terminating the program
// otherwise some events may be lost.
func (client *Client) Close() {
if !client.IsEnabled() {
return
}
if client.telemetryProcessor != nil {
client.telemetryProcessor.Close(5 * time.Second)
}
@@ -875,6 +948,9 @@ func (client *Client) EventFromCheckIn(checkIn *CheckIn, monitorConfig *MonitorC
}
func (client *Client) SetSDKIdentifier(identifier string) {
if !client.IsEnabled() {
return
}
client.mu.Lock()
defer client.mu.Unlock()
+4 -4
View File
@@ -43,7 +43,7 @@ func DynamicSamplingContextFromTransaction(span *Span) DynamicSamplingContext {
scope := hub.Scope()
client := hub.Client()
if client == nil || scope == nil {
if !client.IsEnabled() || scope == nil {
return DynamicSamplingContext{
Entries: map[string]string{},
Frozen: false,
@@ -53,7 +53,7 @@ func DynamicSamplingContextFromTransaction(span *Span) DynamicSamplingContext {
entries := make(map[string]string)
if traceID := span.TraceID.String(); traceID != "" {
entries["trace_id"] = traceID
entries[traceIDContextKey] = traceID
}
if sampleRate := span.sampleRate; sampleRate != 0 {
entries["sample_rate"] = strconv.FormatFloat(sampleRate, 'f', -1, 64)
@@ -122,7 +122,7 @@ func (d DynamicSamplingContext) String() string {
func DynamicSamplingContextFromScope(scope *Scope, client *Client) DynamicSamplingContext {
entries := map[string]string{}
if client == nil || scope == nil {
if !client.IsEnabled() || scope == nil {
return DynamicSamplingContext{
Entries: entries,
Frozen: false,
@@ -132,7 +132,7 @@ func DynamicSamplingContextFromScope(scope *Scope, client *Client) DynamicSampli
propagationContext := scope.propagationContext
if traceID := propagationContext.TraceID.String(); traceID != "" {
entries["trace_id"] = traceID
entries[traceIDContextKey] = traceID
}
if sampleRate := client.options.TracesSampleRate; sampleRate != 0 {
entries["sample_rate"] = strconv.FormatFloat(sampleRate, 'f', -1, 64)
+1 -1
View File
@@ -20,7 +20,7 @@ type visited struct {
func (v *visited) seenError(err error) bool {
t := reflect.ValueOf(err)
if t.Kind() == reflect.Ptr && !t.IsNil() {
if t.Kind() == reflect.Pointer && !t.IsNil() {
ptr := t.Pointer()
if _, ok := v.ptrs[ptr]; ok {
return true
+1
View File
@@ -2,6 +2,7 @@ go 1.25.0
use (
.
./cron
./crosstest
./echo
./fasthttp
+18
View File
@@ -1,5 +1,7 @@
cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4=
cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
cel.dev/expr v0.25.2/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
cloud.google.com/go/auth v0.18.2/go.mod h1:xD+oY7gcahcu7G2SG2DsBerfFxgPAJz17zz2joOFF3M=
cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k=
cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs=
cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=
@@ -14,6 +16,7 @@ git.sr.ht/~sbinet/gg v0.6.0/go.mod h1:uucygbfC9wVPQIfrmwM2et0imr8L7KQWywX0xpFMm9
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0 h1:DHa2U07rk8syqvCge0QIGMCE1WxGj9njT44GH7zNJLQ=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0/go.mod h1:P4WPRUkOhJC13W//jWpyfJNDAIpvRbAUIYLX/4jtlE0=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.32.0/go.mod h1:RD2SsorTmYhF6HkTmDw7KmPYQk8OBYwTkuasChwv7R4=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.33.0/go.mod h1:pJTkW8hEUIIi3Pf65lPZOnn4Y81yCllX6IWk2jNXdkM=
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/PuerkitoBio/goquery v1.8.1 h1:uQxhNlArOIdbrH1tr0UXwdVFgDcZDrZVdcpygAcwmWM=
@@ -60,6 +63,7 @@ github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJP
github.com/envoyproxy/protoc-gen-validate v1.3.0 h1:TvGH1wof4H33rezVKWSpqKz5NXWg5VPuZ0uONDT6eb4=
github.com/envoyproxy/protoc-gen-validate v1.3.0/go.mod h1:HvYl7zwPa5mffgyeTUHA9zHIH36nmrm7oCbo4YKoSWA=
github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0=
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs=
github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
@@ -85,6 +89,9 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/gofuzz v1.0.0 h1:A8PeW59pxE9IoFRqBp37U+mSNaQoZ46F1f0f863XSXw=
github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
github.com/googleapis/enterprise-certificate-proxy v0.3.11/go.mod h1:RFV7MUdlb7AgEq2v7FmMCfeSMCllAzWxFgRdusoGks8=
github.com/googleapis/gax-go/v2 v2.17.0/go.mod h1:mzaqghpQp4JDh3HvADwrat+6M3MOIDp5YKHhb9PAgDY=
github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ=
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
@@ -138,6 +145,7 @@ github.com/spf13/afero v1.10.0 h1:EaGW2JJh15aKOejeuJ+wpFSHnbd7GE6Wvp3TsNhb6LY=
github.com/spf13/afero v1.10.0/go.mod h1:UBogFpq8E9Hx+xc5CNTTEpTnuHVmXDwZcZcE1eb/UhQ=
github.com/spiffe/go-spiffe/v2 v2.6.0 h1:l+DolpxNWYgruGQVV0xsfeya3CsC7m8iBzDnMpsbLuo=
github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xIx7lEzqblHEs=
github.com/spiffe/go-spiffe/v2 v2.7.0/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U=
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
github.com/tailscale/depaware v0.0.0-20210622194025-720c4b409502 h1:34icjjmqJ2HPjrSuJYEkdZ+0ItmGQAQ75cRHIiftIyE=
github.com/tdewolff/argp v0.0.0-20240126212256-acdb2fb50090 h1:ok0U1tNDp9ICD93bMrZuFtHLwDoW+5nfSfF8e/x36Y0=
@@ -161,9 +169,13 @@ go.etcd.io/bbolt v1.3.7/go.mod h1:N9Mkw9X8x5fupy0IKsmuqVtoGDyxsaDlbk4Rd05IAQw=
go.opentelemetry.io/contrib/detectors/gcp v1.39.0 h1:kWRNZMsfBHZ+uHjiH4y7Etn2FK26LAGkNFw7RHv1DhE=
go.opentelemetry.io/contrib/detectors/gcp v1.39.0/go.mod h1:t/OGqzHBa5v6RHZwrDBJ2OirWc+4q/w2fTbLZwAKjTk=
go.opentelemetry.io/contrib/detectors/gcp v1.43.0/go.mod h1:RyaZMFY7yi1kAs45S6mbFGz8O8rqB0dTY14uzvG4LCs=
go.opentelemetry.io/contrib/detectors/gcp v1.44.0/go.mod h1:tNAsgd8avTGke1+MndXlU5Cru4PQ9Ai/cCNWQv/ZJ/s=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.28.0/go.mod h1:rmgy+3RHxRZMyY0jjAJShp2zgEdOqj2AO7U0pYmeQ7U=
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
golang.org/x/image v0.25.0 h1:Y6uW6rH1y5y/LK1J8BPWZtr6yZ7hrsy6hFrXjgsc2fQ=
golang.org/x/image v0.25.0/go.mod h1:tCAmOEGthTtkalusGp1g3xa2gke8J6c2N565dTyl9Rs=
golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY=
@@ -172,10 +184,12 @@ golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU=
golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs=
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
@@ -184,6 +198,7 @@ golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
@@ -199,6 +214,7 @@ golang.org/x/term v0.41.0/go.mod h1:3pfBgksrReYfZ5lvYM0kSO0LIkAl4Yl2bXOkKP7Ec2A=
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
@@ -212,11 +228,13 @@ golang.org/x/tools v0.43.0/go.mod h1:uHkMso649BX2cZK6+RpuIPXS3ho2hZo4FVwfoy1vIk0
golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=
golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
gonum.org/v1/plot v0.15.2 h1:Tlfh/jBk2tqjLZ4/P8ZIwGrLEWQSPDLRm/SNWKNXiGI=
gonum.org/v1/plot v0.15.2/go.mod h1:DX+x+DWso3LTha+AdkJEv5Txvi+Tql3KAGkehP0/Ubg=
gonum.org/v1/tools v0.0.0-20200318103217-c168b003ce8c h1:cJWOvXtcaFSGXz2F4z2AMM0VV7edDDGrxb5GLQH7ayQ=
gonum.org/v1/tools v0.0.0-20200318103217-c168b003ce8c/go.mod h1:fy6Otjqbk477ELp8IXTpw1cObQtLbRCBVonY+bTTfcM=
google.golang.org/genproto v0.0.0-20260128011058-8636f8732409 h1:VQZ/yAbAtjkHgH80teYd2em3xtIkkHd7ZhqfH2N9CsM=
google.golang.org/genproto/googleapis/api v0.0.0-20260120221211-b8f7ae30c516/go.mod h1:p3MLuOwURrGBRoEyFHBT3GjUwaCQVKeNqqWxlcISGdw=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260120221211-b8f7ae30c516/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260401001100-f93e5f3e9f0f/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
+52 -36
View File
@@ -20,7 +20,7 @@ const (
RequestContextKey = contextKey(2)
)
// currentHub is the initial Hub with no Client bound and an empty Scope.
// currentHub is the initial Hub with a no-op Client and an empty Scope.
var currentHub = NewHub(nil, NewScope())
// Hub is the central object that manages scopes and clients.
@@ -58,7 +58,7 @@ func (l *layer) Client() *Client {
func (l *layer) SetClient(c *Client) {
l.mu.Lock()
defer l.mu.Unlock()
l.client = c
l.client = normalizeClient(c)
}
type stack []*layer
@@ -67,7 +67,7 @@ type stack []*layer
func NewHub(client *Client, scope *Scope) *Hub {
hub := Hub{
stack: &stack{{
client: client,
client: normalizeClient(client),
scope: scope,
}},
}
@@ -218,12 +218,12 @@ func (hub *Hub) CaptureEvent(event *Event) *EventID {
// CaptureEventWithHint is like CaptureEvent but additionally accepts an EventHint.
func (hub *Hub) CaptureEventWithHint(event *Event, hint *EventHint) *EventID {
client, scope := hub.Client(), hub.Scope()
if client == nil || scope == nil {
if scope == nil {
return nil
}
eventID := client.CaptureEvent(event, hint, scope)
if event.Type != transactionType && eventID != nil {
if event != nil && event.Type != transactionType && eventID != nil {
hub.mu.Lock()
hub.lastEventID = *eventID
hub.mu.Unlock()
@@ -236,7 +236,7 @@ func (hub *Hub) CaptureEventWithHint(event *Event, hint *EventHint) *EventID {
// Returns EventID if successfully, or nil if there's no Scope or Client available.
func (hub *Hub) CaptureMessage(message string) *EventID {
client, scope := hub.Client(), hub.Scope()
if client == nil || scope == nil {
if scope == nil {
return nil
}
eventID := client.CaptureMessage(message, nil, scope)
@@ -254,7 +254,7 @@ func (hub *Hub) CaptureMessage(message string) *EventID {
// Returns EventID if successfully, or nil if there's no Scope or Client available.
func (hub *Hub) CaptureException(exception error) *EventID {
client, scope := hub.Client(), hub.Scope()
if client == nil || scope == nil {
if scope == nil {
return nil
}
eventID := client.CaptureException(exception, &EventHint{OriginalException: exception}, scope)
@@ -272,13 +272,46 @@ func (hub *Hub) CaptureException(exception error) *EventID {
// Returns CheckInID if the check-in was captured successfully, or nil otherwise.
func (hub *Hub) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig) *EventID {
client, scope := hub.Client(), hub.Scope()
if client == nil {
return nil
}
return client.CaptureCheckIn(checkIn, monitorConfig, scope)
}
// WithMonitor runs fn and reports its outcome as check-ins for the cron
// monitor identified by monitorSlug.
//
// An in_progress check-in carrying monitorConfig is sent before fn runs. When
// monitorConfig is not nil, Sentry creates the monitor if it does not exist,
// or updates its configuration. After fn returns, an ok check-in is sent if
// it returned nil, or an error check-in otherwise, along with the measured
// duration. If fn panics, an error check-in is sent and the panic continues.
//
// The error returned by fn is returned unchanged.
func (hub *Hub) WithMonitor(monitorSlug string, monitorConfig *MonitorConfig, fn func() error) error {
checkInID := hub.CaptureCheckIn(&CheckIn{
MonitorSlug: monitorSlug,
Status: CheckInStatusInProgress,
}, monitorConfig)
start := time.Now()
status := CheckInStatusError
defer func() {
checkIn := &CheckIn{
MonitorSlug: monitorSlug,
Status: status,
Duration: time.Since(start),
}
if checkInID != nil {
checkIn.ID = *checkInID
}
hub.CaptureCheckIn(checkIn, nil)
}()
err := fn()
if err == nil {
status = CheckInStatusOK
}
return err
}
// AddBreadcrumb records a new breadcrumb.
//
// The total number of breadcrumbs that can be recorded are limited by the
@@ -286,12 +319,6 @@ func (hub *Hub) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig) *
func (hub *Hub) AddBreadcrumb(breadcrumb *Breadcrumb, hint *BreadcrumbHint) {
client := hub.Client()
// If there's no client, just store it on the scope straight away
if client == nil {
hub.Scope().AddBreadcrumb(breadcrumb, defaultMaxBreadcrumbs)
return
}
limit := client.options.MaxBreadcrumbs
switch {
case limit < 0:
@@ -321,7 +348,7 @@ func (hub *Hub) Recover(err interface{}) *EventID {
err = recover()
}
client, scope := hub.Client(), hub.Scope()
if client == nil || scope == nil {
if scope == nil {
return nil
}
return client.Recover(err, &EventHint{RecoveredException: err}, scope)
@@ -335,7 +362,7 @@ func (hub *Hub) RecoverWithContext(ctx context.Context, err interface{}) *EventI
err = recover()
}
client, scope := hub.Client(), hub.Scope()
if client == nil || scope == nil {
if scope == nil {
return nil
}
return client.RecoverWithContext(ctx, err, &EventHint{RecoveredException: err}, scope)
@@ -353,19 +380,14 @@ func (hub *Hub) RecoverWithContext(ctx context.Context, err interface{}) *EventI
// the network synchronously, configure it to use the HTTPSyncTransport in the
// call to Init.
func (hub *Hub) Flush(timeout time.Duration) bool {
client := hub.Client()
if client == nil {
return false
}
return client.Flush(timeout)
return hub.Client().Flush(timeout)
}
// FlushWithContext waits until the underlying Transport sends any buffered events
// to the Sentry server, blocking for at most the duration specified by the context.
// It returns false if the context is canceled before the events are sent. In such a case,
// some events may not be delivered.
// to the Sentry server, blocking for at most the duration specified by the
// context. It returns false if capture is disabled or the context is canceled
// before the events are sent. In the latter case, some events may not be
// delivered.
//
// FlushWithContext should be called before terminating the program to ensure no
// events are unintentionally dropped.
@@ -375,13 +397,7 @@ func (hub *Hub) Flush(timeout time.Duration) bool {
// configure the SDK to use HTTPSyncTransport during initialization with Init.
func (hub *Hub) FlushWithContext(ctx context.Context) bool {
client := hub.Client()
if client == nil {
return false
}
return client.FlushWithContext(ctx)
return hub.Client().FlushWithContext(ctx)
}
// GetTraceparent returns the current Sentry traceparent string, to be used as a HTTP header value
@@ -48,6 +48,12 @@ func NewWrapResponseWriter(w http.ResponseWriter, protoMajor int) WrapResponseWr
if fl && hj && rf {
return &httpFancyWriter{bw}
}
if fl && hj {
return &flushHijackWriter{bw}
}
if hj {
return &hijackWriter{bw}
}
}
if fl {
return &flushWriter{bw}
@@ -143,6 +149,36 @@ func (f *flushWriter) Flush() {
var _ http.Flusher = &flushWriter{}
// flushHijackWriter is a HTTP writer that additionally satisfies http.Flusher
// and http.Hijacker, for writers that do not implement io.ReaderFrom.
type flushHijackWriter struct {
basicWriter
}
func (f *flushHijackWriter) Flush() {
f.wroteHeader = true
f.ResponseWriter.(http.Flusher).Flush()
}
func (f *flushHijackWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return f.ResponseWriter.(http.Hijacker).Hijack()
}
var _ http.Flusher = &flushHijackWriter{}
var _ http.Hijacker = &flushHijackWriter{}
// hijackWriter is a HTTP writer that additionally satisfies http.Hijacker, for
// writers that implement neither http.Flusher nor io.ReaderFrom.
type hijackWriter struct {
basicWriter
}
func (f *hijackWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return f.ResponseWriter.(http.Hijacker).Hijack()
}
var _ http.Hijacker = &hijackWriter{}
// httpFancyWriter is a HTTP writer that additionally satisfies
// http.Flusher, http.Hijacker, and io.ReaderFrom. It exists for the common case
// of wrapping the http.ResponseWriter that package http gives you, in order to
+12 -8
View File
@@ -3,6 +3,7 @@ package protocol
import (
"encoding/json"
"fmt"
"net"
"net/url"
"strconv"
"strings"
@@ -210,17 +211,20 @@ func (dsn *Dsn) SetOrgID(orgID uint64) {
// GetAPIURL returns the URL of the envelope endpoint of the project
// associated with the DSN.
func (dsn Dsn) GetAPIURL() *url.URL {
var rawURL string
rawURL += fmt.Sprintf("%s://%s", dsn.scheme, dsn.host)
host := dsn.host
port := ""
if dsn.port != dsn.scheme.defaultPort() {
rawURL += fmt.Sprintf(":%d", dsn.port)
port = strconv.Itoa(dsn.port)
}
if dsn.path != "" {
rawURL += dsn.path
// JoinHostPort correctly adds brackets for IPv6 hosts. However with an
// empty port it leaves a trailing ":", which we trim to omit the default port.
host = net.JoinHostPort(host, port)
host = strings.TrimSuffix(host, ":")
return &url.URL{
Scheme: string(dsn.scheme),
Host: host,
Path: dsn.path + "/api/" + dsn.projectID + "/envelope/",
}
rawURL += fmt.Sprintf("/api/%s/%s/", dsn.projectID, "envelope")
parsedURL, _ := url.Parse(rawURL)
return parsedURL
}
// RequestHeaders returns all the necessary headers that have to be used in the transport when sending events
+26 -2
View File
@@ -26,6 +26,9 @@ type Scheduler struct {
cancel context.CancelFunc
processingWg sync.WaitGroup
// processing serializes buffer-to-transport handoffs and allows cancelable waits.
processing chan struct{}
mu sync.Mutex
cond *sync.Cond
startOnce sync.Once
@@ -79,6 +82,7 @@ func NewScheduler(
currentCycle: currentCycle,
ctx: ctx,
cancel: cancel,
processing: make(chan struct{}, 1),
}
s.cond = sync.NewCond(&s.mu)
@@ -145,7 +149,9 @@ func (s *Scheduler) Flush(timeout time.Duration) bool {
}
func (s *Scheduler) FlushWithContext(ctx context.Context) bool {
s.flushBuffers()
if !s.flushBuffers(ctx) {
return false
}
return s.transport.FlushWithContext(ctx)
}
@@ -193,6 +199,13 @@ func (s *Scheduler) hasWork() bool {
}
func (s *Scheduler) processNextBatch() {
select {
case s.processing <- struct{}{}:
defer func() { <-s.processing }()
case <-s.ctx.Done():
return
}
if len(s.currentCycle) == 0 {
return
}
@@ -290,12 +303,23 @@ func (s *Scheduler) sendItem(item protocol.EnvelopeConvertible) {
}
}
func (s *Scheduler) flushBuffers() {
func (s *Scheduler) flushBuffers(ctx context.Context) bool {
select {
case s.processing <- struct{}{}:
defer func() { <-s.processing }()
case <-ctx.Done():
return false
}
for category, buffer := range s.buffers {
if ctx.Err() != nil {
return false
}
if !buffer.IsEmpty() {
s.processItems(buffer, category, true)
}
}
return ctx.Err() == nil
}
func (s *Scheduler) isRateLimited(category ratelimit.Category) bool {
+2 -2
View File
@@ -60,7 +60,7 @@ func NewLogger(ctx context.Context) Logger { // nolint: dupl
}
client := hub.Client()
if client != nil {
if client.IsEnabled() {
// Build default attrs
serverAddr := client.options.ServerName
if serverAddr == "" {
@@ -111,7 +111,7 @@ func (l *sentryLogger) log(ctx context.Context, level LogLevel, severity int, me
hub = l.hub
}
client := hub.Client()
if client == nil {
if !client.IsEnabled() {
return
}
+2 -2
View File
@@ -55,7 +55,7 @@ func NewMeter(ctx context.Context) Meter {
hub = CurrentHub()
}
client := hub.Client()
if client != nil {
if client.IsEnabled() {
// build default attrs
serverAddr := client.options.ServerName
if serverAddr == "" {
@@ -110,7 +110,7 @@ func (m *sentryMeter) emit(ctx context.Context, metricType MetricType, name stri
}
client := hub.Client()
if client == nil {
if !client.IsEnabled() {
return
}
+7 -2
View File
@@ -4,6 +4,11 @@ import (
"crypto/rand"
)
const (
traceIDContextKey = "trace_id"
spanIDContextKey = "span_id"
)
type PropagationContext struct {
TraceID TraceID `json:"trace_id"`
SpanID SpanID `json:"span_id"`
@@ -13,8 +18,8 @@ type PropagationContext struct {
func (p PropagationContext) Map() map[string]interface{} {
m := map[string]interface{}{
"trace_id": p.TraceID,
"span_id": p.SpanID,
traceIDContextKey: p.TraceID,
spanIDContextKey: p.SpanID,
}
if p.ParentSpanID != zeroSpanID {
+33 -13
View File
@@ -30,7 +30,15 @@ import (
// an event for reporting, the current client adds information from the current
// scope into the event.
type Scope struct {
mu sync.RWMutex
mu sync.RWMutex
// eventProcessors are retained by Clear and inherited by Clone.
eventProcessors []EventProcessor
// scopeData keeps track of all scope specific data
scopeData
}
type scopeData struct {
attributes map[string]attribute.Value
breadcrumbs []*Breadcrumb
attachments []*Attachment
@@ -49,7 +57,6 @@ type Scope struct {
// size.
Overflow() bool
}
eventProcessors []EventProcessor
propagationContext PropagationContext
span *Span
@@ -57,14 +64,18 @@ type Scope struct {
// NewScope creates a new Scope.
func NewScope() *Scope {
return &Scope{
return &Scope{scopeData: newScopeData(NewPropagationContext())}
}
func newScopeData(propagationContext PropagationContext) scopeData {
return scopeData{
attributes: make(map[string]attribute.Value),
breadcrumbs: make([]*Breadcrumb, 0),
attachments: make([]*Attachment, 0),
tags: make(map[string]string),
contexts: make(map[string]Context),
fingerprint: make([]string, 0),
propagationContext: NewPropagationContext(),
propagationContext: propagationContext,
}
}
@@ -282,6 +293,7 @@ func (scope *Scope) Clone() *Scope {
clone := NewScope()
clone.user = scope.user
clone.user.Data = maps.Clone(scope.user.Data)
clone.breadcrumbs = make([]*Breadcrumb, len(scope.breadcrumbs))
copy(clone.breadcrumbs, scope.breadcrumbs)
clone.attachments = make([]*Attachment, len(scope.attachments))
@@ -300,9 +312,16 @@ func (scope *Scope) Clone() *Scope {
return clone
}
// Clear removes the data from the current scope. Not safe for concurrent use.
// Clear removes enrichment data while preserving event processors and trace
// correlation. It is safe for concurrent use.
func (scope *Scope) Clear() {
*scope = *NewScope()
scope.mu.Lock()
defer scope.mu.Unlock()
propagationContext := scope.propagationContext
span := scope.span
scope.scopeData = newScopeData(propagationContext)
scope.span = span
}
// AddEventProcessor adds an event processor to the current scope.
@@ -375,7 +394,7 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client)
event.Contexts["trace"] = scope.propagationContext.Map()
dsc := scope.propagationContext.DynamicSamplingContext
if !dsc.HasEntries() && client != nil {
if !dsc.HasEntries() && client.IsEnabled() {
dsc = DynamicSamplingContextFromScope(scope, client)
}
event.sdkMetaData.dsc = dsc
@@ -383,7 +402,7 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client)
// If an external trace resolver is registered (e.g. OTel), override
// trace/span IDs from the hint context or the scope's request context.
if client != nil {
if client.IsEnabled() {
var ctx context.Context
if hint != nil {
ctx = hint.Context
@@ -393,13 +412,14 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client)
}
if traceID, spanID, ok := client.externalTraceContextFromContext(ctx); event.Type != transactionType && ok {
traceCtx := event.Contexts["trace"]
traceCtx["trace_id"] = traceID.String()
traceCtx["span_id"] = spanID.String()
traceCtx[traceIDContextKey] = traceID.String()
traceCtx[spanIDContextKey] = spanID.String()
}
}
if event.User.IsEmpty() {
event.User = scope.user
event.User.Data = maps.Clone(scope.user.Data)
}
if len(event.Fingerprint) == 0 {
@@ -434,7 +454,7 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client)
event = processor(event, hint)
if event == nil {
debuglog.Printf("Event dropped by one of the Scope EventProcessors: %s\n", id)
if client != nil {
if client.IsEnabled() {
client.reportRecorder.RecordOne(report.ReasonEventProcessor, category)
if category == ratelimit.CategoryTransaction {
client.reportRecorder.Record(report.ReasonEventProcessor, ratelimit.CategorySpan, int64(spanCountBefore))
@@ -443,7 +463,7 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client)
return nil
}
if droppedSpans := spanCountBefore - event.GetSpanCount(); droppedSpans > 0 {
if client != nil {
if client.IsEnabled() {
client.reportRecorder.Record(report.ReasonEventProcessor, ratelimit.CategorySpan, int64(droppedSpans))
}
}
@@ -524,7 +544,7 @@ func resolveTrace(scope *Scope, client *Client, ctxs ...context.Context) (traceI
if ctx == nil {
continue
}
if client != nil {
if client.IsEnabled() {
if traceID, spanID, ok := client.externalTraceContextFromContext(ctx); ok {
return traceID, spanID
}
+25 -4
View File
@@ -6,7 +6,7 @@ import (
)
// The version of the SDK.
const SDKVersion = "0.49.0"
const SDKVersion = "0.50.0"
// apiVersion is the minimum version of the Sentry API compatible with the
// sentry-go SDK.
@@ -54,6 +54,26 @@ func CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig) *EventID {
return hub.CaptureCheckIn(checkIn, monitorConfig)
}
// WithMonitor runs fn and reports its outcome as check-ins for the cron
// monitor identified by monitorSlug, creating or updating the monitor with
// monitorConfig when it is not nil. It is a shorthand for
// CurrentHub().WithMonitor.
//
// Example:
//
// err := sentry.WithMonitor("nightly-cleanup", &sentry.MonitorConfig{
// Schedule: sentry.CrontabSchedule("0 3 * * *"),
// CheckInMargin: 5,
// MaxRuntime: 30,
// Timezone: "UTC",
// }, func() error {
// return cleanup()
// })
func WithMonitor(monitorSlug string, monitorConfig *MonitorConfig, fn func() error) error {
hub := CurrentHub()
return hub.WithMonitor(monitorSlug, monitorConfig, fn)
}
// CaptureEvent captures an event on the currently active client if any.
//
// The event must already be assembled. Typically code would instead use
@@ -129,9 +149,10 @@ func Flush(timeout time.Duration) bool {
}
// FlushWithContext waits until the underlying Transport sends any buffered events
// to the Sentry server, blocking for at most the duration specified by the context.
// It returns false if the context is canceled before the events are sent. In such a case,
// some events may not be delivered.
// to the Sentry server, blocking for at most the duration specified by the
// context. It returns false if capture is disabled or the context is canceled
// before the events are sent. In the latter case, some events may not be
// delivered.
//
// FlushWithContext should be called before terminating the program to ensure no
// events are unintentionally dropped.
+1 -1
View File
@@ -18,7 +18,7 @@ type spanRecorder struct {
// span tree.
func (r *spanRecorder) record(s *Span) {
maxSpans := defaultMaxSpans
if client := CurrentHub().Client(); client != nil {
if client := CurrentHub().Client(); client.IsEnabled() {
maxSpans = client.options.MaxSpans
}
r.mu.Lock()
+4 -4
View File
@@ -551,7 +551,7 @@ func (s *Span) updateFromBaggage(header []byte) {
func (s *Span) clientOptions() *ClientOptions {
client := hubFromContext(s.ctx).Client()
if client != nil {
if client.IsEnabled() {
return &client.options
}
return &ClientOptions{}
@@ -933,8 +933,8 @@ type TraceContext struct {
func (tc TraceContext) Map() map[string]interface{} {
m := map[string]interface{}{
"trace_id": tc.TraceID,
"span_id": tc.SpanID,
traceIDContextKey: tc.TraceID,
spanIDContextKey: tc.SpanID,
}
if tc.ParentSpanID != [8]byte{} {
@@ -1202,7 +1202,7 @@ func HTTPtoSpanStatus(code int) SpanStatus {
}
func shouldContinueTrace(client *Client, dsc DynamicSamplingContext) bool {
if client == nil {
if !client.IsEnabled() {
return true
}
+4 -1
View File
@@ -63,6 +63,7 @@ const (
ChineseFirstNameTag = "chinese_first_name"
ChineseLastNameTag = "chinese_last_name"
ChineseNameTag = "chinese_name"
ChinesePhoneNumberTag = "chinese_phone_number"
GENDER = "gender"
UnixTimeTag = "unix_time"
DATE = "date"
@@ -107,7 +108,7 @@ const (
var PriorityTags = []string{ID, HyphenatedID, EmailTag, MacAddressTag, DomainNameTag, UserNameTag, URLTag, IPV4Tag,
IPV6Tag, PASSWORD, JWT, CountryInfoTag, LATITUDE, LONGITUDE, CreditCardNumber, CreditCardType, PhoneNumber, TollFreeNumber,
E164PhoneNumberTag, TitleMaleTag, TitleFemaleTag, FirstNameTag, FirstNameMaleTag, FirstNameFemaleTag, LastNameTag,
NAME, ChineseFirstNameTag, ChineseLastNameTag, ChineseNameTag, GENDER, UnixTimeTag, DATE, TIME, MonthNameTag,
NAME, ChineseFirstNameTag, ChineseLastNameTag, ChineseNameTag, ChinesePhoneNumberTag, GENDER, UnixTimeTag, DATE, TIME, MonthNameTag,
YEAR, DayOfWeekTag, DayOfMonthTag, TIMESTAMP, CENTURY, TIMEZONE, TimePeriodTag, WORD, SENTENCE, PARAGRAPH,
CurrencyTag, AmountTag, AmountWithCurrencyTag, SKIP, Length, SliceLength, Language, BoundaryStart, BoundaryEnd, ONEOF, BloodTypeTag,
UserAgentTag,
@@ -169,6 +170,7 @@ func initDefaultTag() {
defaultTag.Store(ChineseFirstNameTag, ChineseFirstNameTag)
defaultTag.Store(ChineseLastNameTag, ChineseLastNameTag)
defaultTag.Store(ChineseNameTag, ChineseNameTag)
defaultTag.Store(ChinesePhoneNumberTag, ChinesePhoneNumberTag)
defaultTag.Store(GENDER, GENDER)
defaultTag.Store(UnixTimeTag, UnixTimeTag)
defaultTag.Store(DATE, DATE)
@@ -220,6 +222,7 @@ func initMapperTagDefault() {
mapperTag.Store(ChineseFirstNameTag, GetPerson().ChineseFirstName)
mapperTag.Store(ChineseLastNameTag, GetPerson().ChineseLastName)
mapperTag.Store(ChineseNameTag, GetPerson().ChineseName)
mapperTag.Store(ChinesePhoneNumberTag, GetPhoner().ChinesePhoneNumber)
mapperTag.Store(GENDER, GetPerson().Gender)
mapperTag.Store(UnixTimeTag, GetDateTimer().UnixTime)
mapperTag.Store(DATE, GetDateTimer().Date)
+34
View File
@@ -9,6 +9,20 @@ import (
"github.com/go-faker/faker/v4/pkg/slice"
)
// chineseMobilePrefixes holds the 3-digit prefixes of Mainland China mobile
// numbers, allocated to China Mobile, China Unicom, China Telecom and China
// Broadnet (including MVNO & IoT segments). Each prefix is followed by 8
// subscriber digits to form an 11-digit number.
var chineseMobilePrefixes = []string{
"130", "131", "132", "133", "134", "135", "136", "137", "138", "139",
"145", "146", "147", "148", "149",
"150", "151", "152", "153", "155", "156", "157", "158", "159",
"162", "165", "166", "167",
"170", "171", "172", "173", "174", "175", "176", "177", "178",
"180", "181", "182", "183", "184", "185", "186", "187", "188", "189",
"190", "191", "192", "193", "195", "196", "197", "198", "199",
}
// GetPhoner serves as a constructor for Phoner interface
func GetPhoner() Phoner {
phone := &Phone{}
@@ -20,6 +34,7 @@ type Phoner interface {
PhoneNumber(v reflect.Value) (any, error)
TollFreePhoneNumber(v reflect.Value) (any, error)
E164PhoneNumber(v reflect.Value) (any, error)
ChinesePhoneNumber(v reflect.Value) (any, error)
}
// Phone struct
@@ -95,3 +110,22 @@ func E164PhoneNumber(opts ...options.OptionFunc) string {
return p.e164PhoneNumber()
}, opts...).(string)
}
func (p Phone) chinesePhoneNumber() string {
prefix := chineseMobilePrefixes[rand.Intn(len(chineseMobilePrefixes))]
return prefix + randomStringNumber(8)
}
// ChinesePhoneNumber generates a Mainland-China mobile phone number of the
// form "13812345678" (11 digits, starting with a valid operator prefix)
func (p Phone) ChinesePhoneNumber(v reflect.Value) (any, error) {
return p.chinesePhoneNumber(), nil
}
// ChinesePhoneNumber get fake Chinese phone number
func ChinesePhoneNumber(opts ...options.OptionFunc) string {
return singleFakeData(ChinesePhoneNumberTag, func() any {
p := Phone{}
return p.chinesePhoneNumber()
}, opts...).(string)
}
+7 -5
View File
@@ -139,11 +139,13 @@ func main() {
fmt.Println(l.CardinalPluralRule(1.0, 1))
fmt.Println(l.CardinalPluralRule(3, 0))
// Ordinal Plural Rules
fmt.Println(l.OrdinalPluralRule(21, 0)) // 21st
fmt.Println(l.OrdinalPluralRule(22, 0)) // 22nd
fmt.Println(l.OrdinalPluralRule(33, 0)) // 33rd
fmt.Println(l.OrdinalPluralRule(34, 0)) // 34th
// Ordinal Plural Rules. The method returns the locales/plurals.Rule
// (e.g. One, Two, Few, Other) for the number; converting that rule into
// the actual suffix ("st", "nd", "rd", "th") is left to the caller.
fmt.Println(l.OrdinalPluralRule(21, 0)) // One (-> "21st")
fmt.Println(l.OrdinalPluralRule(22, 0)) // Two (-> "22nd")
fmt.Println(l.OrdinalPluralRule(33, 0)) // Few (-> "33rd")
fmt.Println(l.OrdinalPluralRule(34, 0)) // Other (-> "34th")
// Range Plural Rules
fmt.Println(l.RangePluralRule(1, 0, 1, 0)) // 1-1
+12 -16
View File
@@ -498,10 +498,9 @@ func (en *en) FmtTimeShort(t time.Time) string {
b := make([]byte, 0, 32)
h := t.Hour()
if h > 12 {
h -= 12
h := t.Hour() % 12
if h == 0 {
h = 12
}
b = strconv.AppendInt(b, int64(h), 10)
@@ -528,10 +527,9 @@ func (en *en) FmtTimeMedium(t time.Time) string {
b := make([]byte, 0, 32)
h := t.Hour()
if h > 12 {
h -= 12
h := t.Hour() % 12
if h == 0 {
h = 12
}
b = strconv.AppendInt(b, int64(h), 10)
@@ -565,10 +563,9 @@ func (en *en) FmtTimeLong(t time.Time) string {
b := make([]byte, 0, 32)
h := t.Hour()
if h > 12 {
h -= 12
h := t.Hour() % 12
if h == 0 {
h = 12
}
b = strconv.AppendInt(b, int64(h), 10)
@@ -607,10 +604,9 @@ func (en *en) FmtTimeFull(t time.Time) string {
b := make([]byte, 0, 32)
h := t.Hour()
if h > 12 {
h -= 12
h := t.Hour() % 12
if h == 0 {
h = 12
}
b = strconv.AppendInt(b, int64(h), 10)
+13 -10
View File
@@ -98,7 +98,7 @@ type Translator interface {
// returns the locales narrow weekday given the 'weekday' provided
WeekdayNarrow(weekday time.Weekday) string
// WeekdaysNarrowreturns the locales narrow weekdays
// WeekdaysNarrow returns the locales narrow weekdays
WeekdaysNarrow() []string
// returns the locales short weekday given the 'weekday' provided
@@ -113,7 +113,7 @@ type Translator interface {
// returns the locales wide weekdays
WeekdaysWide() []string
// The following Functions are common Formatting functionsfor the Translator's Locale
// The following Functions are common Formatting functions for the Translator's Locale
// returns 'num' with digits/precision of 'v' for locale and handles both Whole and Real numbers based on 'v'
FmtNumber(num float64, v uint64) string
@@ -228,14 +228,14 @@ func W(n float64, v uint64) (w int64) {
s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64)
// with either be '0' or '0.xxxx', so if 1 then w will be zero
// will either be '0' or '0.xxxx', so if 1 then w will be zero
// otherwise need to parse
if len(s) != 1 {
s = s[2:]
end := len(s) + 1
end := 0
for i := end; i >= 0; i-- {
for i := len(s) - 1; i >= 0; i-- {
if s[i] != '0' {
end = i + 1
break
@@ -253,7 +253,7 @@ func F(n float64, v uint64) (f int64) {
s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64)
// with either be '0' or '0.xxxx', so if 1 then f will be zero
// will either be '0' or '0.xxxx', so if 1 then f will be zero
// otherwise need to parse
if len(s) != 1 {
@@ -270,14 +270,14 @@ func T(n float64, v uint64) (t int64) {
s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64)
// with either be '0' or '0.xxxx', so if 1 then t will be zero
// will either be '0' or '0.xxxx', so if 1 then t will be zero
// otherwise need to parse
if len(s) != 1 {
s = s[2:]
end := len(s) + 1
end := 0
for i := end; i >= 0; i-- {
for i := len(s) - 1; i >= 0; i-- {
if s[i] != '0' {
end = i + 1
break
@@ -286,8 +286,11 @@ func T(n float64, v uint64) (t int64) {
// ignoring error, because it can't fail as we generated
// the string internally from a real number
t, _ = strconv.ParseInt(s[:end], 10, 64)
if end > 0 {
t, _ = strconv.ParseInt(s[:end], 10, 64)
}
}
return
}
+42
View File
@@ -0,0 +1,42 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project
`universal-translator` (`ut`) is a Go i18n library that wraps `github.com/go-playground/locales` (CLDR locale data) to provide translation registration, plural rule handling (cardinal, ordinal, range), and `{0}`-style parameter substitution. Translations can be registered programmatically or loaded from JSON files.
## Commands
```bash
# Run tests with race detection and coverage
make test
# Run benchmarks
make bench
# Lint
make lint # or: golangci-lint run
# Run a single test
go test -run TestTranslatorAdd -race -v ./...
```
## Architecture
Flat package `ut` at the repo root — no sub-packages.
- **`universal_translator.go`** — `UniversalTranslator` struct: holds a `map[string]Translator` (keyed by lowercased locale) plus a fallback. Constructor: `New(fallback, ...supportedLocales)`. Methods: `FindTranslator`, `GetTranslator`, `AddTranslator`, `VerifyTranslations`.
- **`translator.go`** — `Translator` interface (embeds `locales.Translator`) and private `translator` impl. Registration: `Add`, `AddCardinal`, `AddOrdinal`, `AddRange`. Resolution: `T`, `C`, `O`, `R`. Each translation key is `interface{}` (string or int). Parameter substitution indexes are precomputed at registration time via `transText`.
- **`import_export.go`** — JSON import/export. `Export` writes per-locale JSON files. `Import` reads them (supports recursive directory traversal). `ImportByReader` for streaming.
- **`errors.go`** — Typed error structs: `ErrUnknownTranslation`, `ErrExistingTranslator`, `ErrConflictingTranslation`, `ErrRangeTranslation`, `ErrOrdinalTranslation`, `ErrCardinalTranslation`, `ErrMissingPluralTranslation`, `ErrMissingBracket`, `ErrBadParamSyntax`, `ErrMissingLocale`, `ErrBadPluralDefinition`.
Note: the private field names `cardinalTanslations`, `ordinalTanslations`, `rangeTanslations` are historical typos — do not "fix" them as it would break serialization/deserialization compatibility.
## Testing
Tests live at the repo root alongside source files. Test data JSON files are in `testdata/`. The library is goroutine-safe for reads once translations are registered — benchmarks in `benchmarks_test.go` test both serial and parallel `T()` calls.
## CI
GitHub Actions (`.github/workflows/workflow.yml`): Go 1.19.x matrix across ubuntu/macos/windows with race detection, coverage via goveralls, and golangci-lint.
+9
View File
@@ -0,0 +1,9 @@
## AI Agents
AI-assisted contributions are welcome but must be clearly attributed. If you are an AI agent or using an AI agent to contribute:
- **Commits**: Include a `Co-Authored-By:` trailer identifying the AI model used.
- **Pull requests and issues**: State that the content was AI-generated or AI-assisted in the description.
- **Code review comments**: Prefix with `[AI]` when posting automated review comments.
Contributions that obscure their AI origin may be closed.
+11
View File
@@ -82,6 +82,17 @@ Help With Tests
To anyone interesting in helping or contributing, I sure could use some help creating tests for each language.
Please see issue [here](https://github.com/go-playground/locales/issues/1) for details.
Supported Go Versions
---------------------
This package is aligned with the [Go release policy](https://go.dev/doc/devel/release) in that support is guaranteed for
the two most recent major versions.
This does not mean the package will not work with older versions of Go, only that we reserve the right to increase the
MSGV(Minimum Supported Go Version) when the need arises to address Security issues/patches, OS issues & support or newly
introduced functionality that would greatly benefit the maintenance and/or usage of this package.
If and when the MSGV is increased it will be done so in a minimum of a `Minor` release bump.
License
------
Distributed under MIT License, please see license file in code for more details.
+5 -2
View File
@@ -8,8 +8,11 @@ import (
)
var (
// ErrUnknowTranslation indicates the translation could not be found
ErrUnknowTranslation = errors.New("Unknown Translation")
// ErrUnknownTranslation indicates the translation could not be found
ErrUnknownTranslation = errors.New("unknown translation")
// Deprecated: Use ErrUnknownTranslation instead.
ErrUnknowTranslation = ErrUnknownTranslation
)
var _ error = new(ErrConflictingTranslation)
+1 -1
View File
@@ -163,7 +163,7 @@ func (t *UniversalTranslator) Import(format ImportExportFormat, dirnameOrFilenam
if err != nil {
return err
}
defer f.Close()
defer func() { _ = f.Close() }()
return t.ImportByReader(format, f)
}
+83 -33
View File
@@ -101,35 +101,87 @@ func (t *translator) Add(key interface{}, text string, override bool) error {
return &ErrConflictingTranslation{locale: t.Locale(), key: key, text: text}
}
lb := strings.Count(text, "{")
rb := strings.Count(text, "}")
if lb != rb {
return &ErrMissingBracket{locale: t.Locale(), key: key, text: text}
indexes, err := parseParamPlaceholders(text, t.Locale(), key)
if err != nil {
return err
}
trans := &transText{
text: text,
}
var idx int
for i := 0; i < lb; i++ {
s := "{" + strconv.Itoa(i) + "}"
idx = strings.Index(text, s)
if idx == -1 {
return &ErrBadParamSyntax{locale: t.Locale(), param: s, key: key, text: text}
}
trans.indexes = append(trans.indexes, idx)
trans.indexes = append(trans.indexes, idx+len(s))
}
t.translations[key] = trans
t.translations[key] = &transText{text: text, indexes: indexes}
return nil
}
// parseParamPlaceholders scans text for {N} placeholders where N is a canonical
// non-negative integer (no leading zeros). Returns triplets [start, end, paramIdx, ...]
// sorted by text position. Requires consecutive param indices starting from 0.
func parseParamPlaceholders(text string, locale string, key interface{}) ([]int, error) {
var indexes []int
seen := make(map[int]struct{})
maxParam := -1
for i := 0; i < len(text); i++ {
if text[i] != '{' {
continue
}
j := i + 1
for j < len(text) && text[j] >= '0' && text[j] <= '9' {
j++
}
digitLen := j - i - 1
if digitLen == 0 {
continue
}
if j >= len(text) {
return nil, &ErrMissingBracket{locale: locale, key: key, text: text}
}
if text[j] != '}' {
i = j - 1
continue
}
if digitLen > 1 && text[i+1] == '0' {
i = j
continue
}
if digitLen > 9 {
i = j
continue
}
n := 0
for k := i + 1; k < j; k++ {
n = n*10 + int(text[k]-'0')
}
indexes = append(indexes, i, j+1, n)
seen[n] = struct{}{}
if n > maxParam {
maxParam = n
}
i = j
}
if len(seen) == 0 {
return nil, nil
}
if maxParam != len(seen)-1 {
for i := 0; i <= maxParam; i++ {
if _, ok := seen[i]; !ok {
return nil, &ErrBadParamSyntax{locale: locale, param: "{" + strconv.Itoa(i) + "}", key: key, text: text}
}
}
}
return indexes, nil
}
// AddCardinal adds a cardinal plural translation for a particular language/locale
// {0} is the only replacement type accepted and only one variable is accepted as
// multiple cannot be used for a plural rule determination, unless it is a range;
@@ -298,20 +350,18 @@ func (t *translator) T(key interface{}, params ...string) (string, error) {
trans, ok := t.translations[key]
if !ok {
return unknownTranslation, ErrUnknowTranslation
return unknownTranslation, ErrUnknownTranslation
}
b := make([]byte, 0, 64)
var start, end, count int
var start, end int
for i := 0; i < len(trans.indexes); i++ {
for i := 0; i < len(trans.indexes); i += 3 {
end = trans.indexes[i]
b = append(b, trans.text[start:end]...)
b = append(b, params[count]...)
i++
start = trans.indexes[i]
count++
b = append(b, params[trans.indexes[i+2]]...)
start = trans.indexes[i+1]
}
b = append(b, trans.text[start:]...)
@@ -324,7 +374,7 @@ func (t *translator) C(key interface{}, num float64, digits uint64, param string
tarr, ok := t.cardinalTanslations[key]
if !ok {
return unknownTranslation, ErrUnknowTranslation
return unknownTranslation, ErrUnknownTranslation
}
rule := t.CardinalPluralRule(num, digits)
@@ -344,7 +394,7 @@ func (t *translator) O(key interface{}, num float64, digits uint64, param string
tarr, ok := t.ordinalTanslations[key]
if !ok {
return unknownTranslation, ErrUnknowTranslation
return unknownTranslation, ErrUnknownTranslation
}
rule := t.OrdinalPluralRule(num, digits)
@@ -365,7 +415,7 @@ func (t *translator) R(key interface{}, num1 float64, digits1 uint64, num2 float
tarr, ok := t.rangeTanslations[key]
if !ok {
return unknownTranslation, ErrUnknowTranslation
return unknownTranslation, ErrUnknownTranslation
}
rule := t.RangePluralRule(num1, digits1, num2, digits2)
@@ -18,6 +18,50 @@ func (e InvalidTemplateError) Error() string {
// Parse parses the string representation of path template
func Parse(tmpl string) (Compiler, error) {
return parse(tmpl)
}
// Segment is a top-level segment of a parsed path template.
type Segment struct {
// FieldPath is the field path bound by a variable segment, e.g. "name"
// for "{name=projects/*}". It is empty for literal and wildcard segments.
FieldPath string
// Value is the literal or wildcard ("*" or "**") of a non-variable
// segment, or the pattern of a variable segment, e.g. "projects/*" for
// "{name=projects/*}". A variable without an explicit pattern, such as
// "{name}", has the pattern "*".
Value string
}
// SplitTemplate parses the string representation of path template and
// returns its top-level segments and its verb. The root template "/" has no
// segments.
func SplitTemplate(tmpl string) (segments []Segment, verb string, err error) {
t, err := parse(tmpl)
if err != nil {
return nil, "", err
}
for _, s := range t.segments {
switch s := s.(type) {
case literal:
if s == eof {
continue
}
segments = append(segments, Segment{Value: string(s)})
case variable:
pattern := make([]string, 0, len(s.segments))
for _, vs := range s.segments {
pattern = append(pattern, vs.String())
}
segments = append(segments, Segment{FieldPath: s.path, Value: strings.Join(pattern, "/")})
default:
segments = append(segments, Segment{Value: s.String()})
}
}
return segments, t.verb, nil
}
func parse(tmpl string) (template, error) {
if !strings.HasPrefix(tmpl, "/") {
return template{}, InvalidTemplateError{tmpl: tmpl, msg: "no leading /"}
}
@@ -28,6 +72,9 @@ func Parse(tmpl string) (Compiler, error) {
if err != nil {
return template{}, InvalidTemplateError{tmpl: tmpl, msg: err.Error()}
}
if err := expectPChars(verb); err != nil {
return template{}, InvalidTemplateError{tmpl: tmpl, msg: fmt.Sprintf("invalid verb: %v", err)}
}
return template{
segments: segs,
+6
View File
@@ -38,6 +38,7 @@ go_library(
"@org_golang_google_protobuf//reflect/protoreflect",
"@org_golang_google_protobuf//reflect/protoregistry",
"@org_golang_google_protobuf//types/known/durationpb",
"@org_golang_google_protobuf//types/known/emptypb",
"@org_golang_google_protobuf//types/known/fieldmaskpb",
"@org_golang_google_protobuf//types/known/structpb",
"@org_golang_google_protobuf//types/known/timestamppb",
@@ -49,13 +50,16 @@ go_test(
name = "runtime_test",
size = "small",
srcs = [
"context_internal_test.go",
"context_test.go",
"convert_test.go",
"errors_test.go",
"fieldmask_empty_object_test.go",
"fieldmask_test.go",
"handler_test.go",
"marshal_httpbodyproto_test.go",
"marshal_json_test.go",
"marshal_jsonpb_bench_test.go",
"marshal_jsonpb_test.go",
"marshal_proto_test.go",
"marshaler_registry_test.go",
@@ -63,6 +67,7 @@ go_test(
"mux_test.go",
"pattern_test.go",
"query_fuzz_test.go",
"query_internal_test.go",
"query_test.go",
],
embed = [":runtime"],
@@ -76,6 +81,7 @@ go_test(
"@org_golang_google_genproto_googleapis_rpc//status",
"@org_golang_google_grpc//:grpc",
"@org_golang_google_grpc//codes",
"@org_golang_google_grpc//credentials/insecure",
"@org_golang_google_grpc//health/grpc_health_v1",
"@org_golang_google_grpc//metadata",
"@org_golang_google_grpc//status",
+76 -14
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/base64"
"fmt"
"math"
"net"
"net/http"
"net/textproto"
@@ -36,6 +37,13 @@ const metadataHeaderBinarySuffix = "-Bin"
const xForwardedFor = "X-Forwarded-For"
const xForwardedHost = "X-Forwarded-Host"
// gRPC metadata keys are lower-case, so these two are appended to the pairs under their
// lower-case spelling. Writing it out as a constant keeps strings.ToLower off the per-request
// path, where it allocated a new string for a compile-time constant on every call, and lets
// metadata.Pairs skip its own lower-casing for these keys as well.
const xForwardedForKey = "x-forwarded-for"
const xForwardedHostKey = "x-forwarded-host"
// DefaultContextTimeout is used for gRPC call context.WithTimeout whenever a Grpc-Timeout inbound
// header isn't present. If the value is 0 the sent `context` will not have a timeout.
var DefaultContextTimeout = 0 * time.Second
@@ -107,6 +115,10 @@ func isValidGRPCMetadataKey(key string) bool {
// This means 0-9 a-z _ - .
// Only lowercase letters are valid in the wire protocol, but the client library will normalize
// uppercase ASCII to lowercase, so uppercase ASCII is also acceptable.
// An empty key is not a valid header name, and gRPC fails the call with one.
if key == "" {
return false
}
bytes := []byte(key) // gRPC validates strings on the byte level, not Unicode.
for _, ch := range bytes {
validLowercaseLetter := ch >= 'a' && ch <= 'z'
@@ -146,7 +158,21 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM
return nil, nil, status.Errorf(codes.InvalidArgument, "invalid grpc-timeout: %s", tm)
}
}
var pairs []string
// Each forwarded header contributes a key and a value, and the two X-Forwarded-* pairs the
// gateway derives below add two more. Sizing for that up front replaces the handful of
// reallocations an empty slice goes through while it doubles.
pairs := make([]string, 0, 2*(len(req.Header)+2))
// For backwards-compatibility, pass through 'authorization' header with no prefix.
// It is added before the header loop so that it is always the first
// "authorization" value: the loop iterates a map, so a header the matcher
// forwards under the same key (Grpc-Metadata-Authorization with the default
// matcher) would otherwise land ahead of it in random order, and a backend
// reading the first value would get the client-forwarded one.
for _, val := range req.Header.Values("Authorization") {
if isValidGRPCMetadataTextValue(val) {
pairs = append(pairs, "authorization", val)
}
}
for key, vals := range req.Header {
key = textproto.CanonicalMIMEHeaderKey(key)
switch key {
@@ -156,11 +182,17 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM
}
for _, val := range vals {
// For backwards-compatibility, pass through 'authorization' header with no prefix.
if key == "Authorization" {
pairs = append(pairs, "authorization", val)
}
if h, ok := mux.incomingHeaderMatcher(key); ok {
// The gateway derives x-forwarded-host and x-forwarded-for below from
// the trusted request (Host / X-Forwarded-* / RemoteAddr), and backends
// rely on those metadata keys for client host/IP decisions. Refuse a
// forwarded header that the matcher strips into one of them (e.g.
// Grpc-Metadata-X-Forwarded-For) so a client cannot slip a spoofed value
// in ahead of the gateway-set one.
if strings.EqualFold(h, xForwardedFor) || strings.EqualFold(h, xForwardedHost) {
grpclog.Errorf("HTTP header %q maps to gateway-reserved metadata key %q; skipping", key, h)
continue
}
if !isValidGRPCMetadataKey(h) {
grpclog.Errorf("HTTP header name %q is not valid as gRPC metadata key; skipping", h)
continue
@@ -182,28 +214,52 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM
}
}
}
if host := req.Header.Get(xForwardedHost); host != "" {
pairs = append(pairs, strings.ToLower(xForwardedHost), host)
} else if req.Host != "" {
pairs = append(pairs, strings.ToLower(xForwardedHost), req.Host)
if host := req.Header.Get(xForwardedHost); host != "" && isValidGRPCMetadataTextValue(host) {
pairs = append(pairs, xForwardedHostKey, host)
} else if req.Host != "" && isValidGRPCMetadataTextValue(req.Host) {
pairs = append(pairs, xForwardedHostKey, req.Host)
}
xff := req.Header.Values(xForwardedFor)
// Validate each X-Forwarded-For value on its own, so that an invalid
// client-supplied value is dropped without also dropping the remote
// address the gateway appends.
var xff []string
for _, value := range req.Header.Values(xForwardedFor) {
if isValidGRPCMetadataTextValue(value) {
xff = append(xff, value)
}
}
if addr := req.RemoteAddr; addr != "" {
if remoteIP, _, err := net.SplitHostPort(addr); err == nil {
if remoteIP, _, err := net.SplitHostPort(addr); err == nil && isValidGRPCMetadataTextValue(remoteIP) {
xff = append(xff, remoteIP)
}
}
if len(xff) > 0 {
pairs = append(pairs, strings.ToLower(xForwardedFor), strings.Join(xff, ", "))
pairs = append(pairs, xForwardedForKey, strings.Join(xff, ", "))
}
if timeout != 0 {
ctx, _ = context.WithTimeout(ctx, timeout)
}
md := metadata.Pairs(pairs...)
var annotated metadata.MD
for _, mda := range mux.metadataAnnotators {
md = metadata.Join(md, mda(ctx, req))
annotated = metadata.Join(annotated, mda(ctx, req))
}
// Annotators are the gateway's own code, so their values replace whatever
// the request headers put under the same key. Joining them after the
// header values would let a client send Grpc-Metadata-<key> and have its
// value read first by a backend that trusts the annotator.
//
// With no annotators registered -- the default -- there is nothing to merge, and
// metadata.Join would rebuild the whole map for nothing: it starts from an empty MD and
// appends every key's values into a fresh slice, so the result is an identical copy of md
// bought with one allocation per key.
if len(annotated) > 0 {
for k := range annotated {
delete(md, strings.ToLower(k))
}
md = metadata.Join(md, annotated)
}
if len(md) == 0 {
return ctx, nil, nil
@@ -302,10 +358,16 @@ func timeoutDecode(s string) (time.Duration, error) {
if !ok {
return 0, fmt.Errorf("timeout unit is not recognized: %q", s)
}
t, err := strconv.ParseInt(s[:size-1], 10, 64)
t, err := strconv.ParseUint(s[:size-1], 10, 64)
if err != nil {
return 0, err
}
// Guard against overflowing time.Duration, which is an int64 nanosecond
// count: without this a large value wraps to a bogus (often negative)
// deadline instead of the long timeout the client asked for.
if t > uint64(math.MaxInt64)/uint64(d) {
return time.Duration(math.MaxInt64), nil
}
return d * time.Duration(t), nil
}
+50 -17
View File
@@ -3,6 +3,7 @@ package runtime
import (
"encoding/base64"
"fmt"
"math"
"strconv"
"strings"
@@ -44,9 +45,40 @@ func BoolSlice(val, sep string) ([]bool, error) {
return values, nil
}
// parseFloat parses a floating point value the way the proto3 JSON mapping
// does: a decimal number, or the exact strings "Infinity", "-Infinity" and
// "NaN". strconv.ParseFloat additionally accepts hexadecimal floats ("0x1p4"),
// underscore digit separators ("1_000") and alternate infinity/NaN spellings
// ("Inf", "nan", "infinity"), none of which protojson (and so the request body
// and backend) accept. Reject those so a value bound from a query or path
// parameter can't differ from the same value sent in the body.
func parseFloat(val string, bitSize int) (float64, error) {
switch val {
case "Infinity":
return math.Inf(1), nil
case "-Infinity":
return math.Inf(-1), nil
case "NaN":
return math.NaN(), nil
}
if strings.ContainsAny(val, "xX_") {
return 0, fmt.Errorf("invalid syntax %q", val)
}
f, err := strconv.ParseFloat(val, bitSize)
if err != nil {
return 0, err
}
// ParseFloat only yields Inf/NaN without an error for the alternate
// spellings handled above; overflow returns a range error instead.
if math.IsInf(f, 0) || math.IsNaN(f) {
return 0, fmt.Errorf("invalid syntax %q", val)
}
return f, nil
}
// Float64 converts the given string representation into representation of a floating point number into float64.
func Float64(val string) (float64, error) {
return strconv.ParseFloat(val, 64)
return parseFloat(val, 64)
}
// Float64Slice converts 'val' where individual floating point numbers are separated by
@@ -66,7 +98,7 @@ func Float64Slice(val, sep string) ([]float64, error) {
// Float32 converts the given string representation of a floating point number into float32.
func Float32(val string) (float32, error) {
f, err := strconv.ParseFloat(val, 32)
f, err := parseFloat(val, 32)
if err != nil {
return 0, err
}
@@ -90,7 +122,7 @@ func Float32Slice(val, sep string) ([]float32, error) {
// Int64 converts the given string representation of an integer into int64.
func Int64(val string) (int64, error) {
return strconv.ParseInt(val, 0, 64)
return strconv.ParseInt(val, 10, 64)
}
// Int64Slice converts 'val' where individual integers are separated by
@@ -110,7 +142,7 @@ func Int64Slice(val, sep string) ([]int64, error) {
// Int32 converts the given string representation of an integer into int32.
func Int32(val string) (int32, error) {
i, err := strconv.ParseInt(val, 0, 32)
i, err := strconv.ParseInt(val, 10, 32)
if err != nil {
return 0, err
}
@@ -134,7 +166,7 @@ func Int32Slice(val, sep string) ([]int32, error) {
// Uint64 converts the given string representation of an integer into uint64.
func Uint64(val string) (uint64, error) {
return strconv.ParseUint(val, 0, 64)
return strconv.ParseUint(val, 10, 64)
}
// Uint64Slice converts 'val' where individual integers are separated by
@@ -154,7 +186,7 @@ func Uint64Slice(val, sep string) ([]uint64, error) {
// Uint32 converts the given string representation of an integer into uint32.
func Uint32(val string) (uint32, error) {
i, err := strconv.ParseUint(val, 0, 32)
i, err := strconv.ParseUint(val, 10, 32)
if err != nil {
return 0, err
}
@@ -176,21 +208,22 @@ func Uint32Slice(val, sep string) ([]uint32, error) {
return values, nil
}
// Bytes converts the given string representation of a byte sequence into a slice of bytes
// A bytes sequence is encoded in URL-safe base64 without padding
// Bytes converts the given string representation of a byte sequence into a slice of bytes.
// Like the protobuf JSON mapping, it accepts standard or URL-safe base64, with or
// without padding.
func Bytes(val string) ([]byte, error) {
b, err := base64.StdEncoding.DecodeString(val)
if err != nil {
b, err = base64.URLEncoding.DecodeString(val)
if err != nil {
return nil, err
}
enc := base64.StdEncoding
if strings.ContainsAny(val, "-_") {
enc = base64.URLEncoding
}
return b, nil
if len(val)%4 != 0 {
enc = enc.WithPadding(base64.NoPadding)
}
return enc.DecodeString(val)
}
// BytesSlice converts 'val' where individual bytes sequences, encoded in URL-safe
// base64 without padding, are separated by 'sep' into a slice of byte slices.
// BytesSlice converts 'val' where individual bytes sequences, encoded in standard or
// URL-safe base64, are separated by 'sep' into a slice of byte slices.
func BytesSlice(val, sep string) ([][]byte, error) {
s := strings.Split(val, sep)
values := make([][]byte, len(s))
+2 -1
View File
@@ -134,7 +134,8 @@ func DefaultHTTPErrorHandler(ctx context.Context, mux *ServeMux, marshaler Marsh
w.Header().Set("Content-Type", contentType)
if s.Code() == codes.Unauthenticated {
w.Header().Set("WWW-Authenticate", s.Message())
// Canonical spelling, so Header.Set does not have to build one.
w.Header().Set("Www-Authenticate", s.Message())
}
buf, merr := marshaler.Marshal(respRw)
+52 -24
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"io"
"sort"
"strings"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
@@ -65,14 +66,16 @@ func FieldMaskFromRequestBody(r io.Reader, msg proto.Message) (*field_mask.Field
}
if isProtobufAnyMessage(fd.Message()) && !fd.IsList() {
_, hasTypeField := v.(map[string]interface{})["@type"]
if hasTypeField {
queue = append(queue, fieldMaskPathItem{path: k})
continue
} else {
vm, _ := v.(map[string]interface{})
if _, hasTypeField := vm["@type"]; !hasTypeField {
return nil, fmt.Errorf("could not find field @type in %q in message %q", k, item.msg.Descriptor().FullName())
}
newPath := string(fd.FullName().Name())
if item.path != "" {
newPath = item.path + "." + newPath
}
queue = append(queue, fieldMaskPathItem{path: newPath})
continue
}
child := fieldMaskPathItem{
@@ -96,10 +99,10 @@ func FieldMaskFromRequestBody(r io.Reader, msg proto.Message) (*field_mask.Field
queue = append(queue, child)
}
}
case ok && len(m) == 0:
fallthrough
case len(item.path) > 0:
// otherwise, it's a leaf node so print its path
// otherwise, it's a leaf node (an empty object counts as one) so
// print its path. The root has no path: an empty body such as {}
// sets nothing, and an empty path is not a valid FieldMask path.
fm.Paths = append(fm.Paths, item.path)
}
}
@@ -126,30 +129,55 @@ func isDynamicProtoMessage(md protoreflect.MessageDescriptor) bool {
// passed in name and json value.
func buildPathsBlindly(name string, in interface{}) []string {
m, ok := in.(map[string]interface{})
if !ok {
if !ok || len(m) == 0 {
return []string{name}
}
// A google.protobuf.Struct/Value field carries arbitrary client JSON, so
// its nesting depth is attacker controlled. Keep each queue entry pointing
// at its parent and its own segment rather than carrying the full path
// string, so a path is concatenated once at the leaf (O(depth)) instead of
// rebuilding the growing prefix at every level (O(depth^2)). A deeply
// nested object otherwise makes this allocate quadratically in the depth
// while producing only a handful of paths.
type pathNode struct {
parent *pathNode
segment string
}
type queueItem struct {
path *pathNode
node map[string]any
}
var paths []string
queue := []fieldMaskPathItem{{path: name, node: m}}
queue := []queueItem{{path: &pathNode{segment: name}, node: m}}
for len(queue) > 0 {
cur := queue[0]
queue = queue[1:]
m, ok := cur.node.(map[string]interface{})
if !ok {
// This should never happen since we should always check that we only add
// nodes of type map[string]interface{} to the queue.
continue
}
for k, v := range m {
if mi, ok := v.(map[string]interface{}); ok {
queue = append(queue, fieldMaskPathItem{path: cur.path + "." + k, node: mi})
} else {
// This is not a struct, so there are no more levels to descend.
curPath := cur.path + "." + k
paths = append(paths, curPath)
for k, v := range cur.node {
child := &pathNode{parent: cur.path, segment: k}
if mi, ok := v.(map[string]any); ok && len(mi) > 0 {
queue = append(queue, queueItem{path: child, node: mi})
continue
}
// No populated object remains, so there are no more levels to
// descend. Walk back to the root to materialize the path once.
var segments []string
n := 0
for p := child; p != nil; p = p.parent {
segments = append(segments, p.segment)
n += len(p.segment) + 1
}
var b strings.Builder
b.Grow(n - 1)
for i := len(segments) - 1; i >= 0; i-- {
b.WriteString(segments[i])
if i > 0 {
b.WriteByte('.')
}
}
paths = append(paths, b.String())
}
}
return paths
+4 -1
View File
@@ -210,7 +210,10 @@ func ForwardResponseMessage(ctx context.Context, mux *ServeMux, marshaler Marsha
}
func requestAcceptsTrailers(req *http.Request) bool {
te := req.Header.Get("TE")
// "Te", not "TE": Header.Get canonicalises the key it is given, and a key that is already
// canonical is returned as is, while any other spelling costs an allocated copy on every
// call. This one runs once per response.
te := req.Header.Get("Te")
return strings.Contains(strings.ToLower(te), "trailers")
}
+99 -3
View File
@@ -5,11 +5,13 @@ import (
"encoding/json"
"fmt"
"io"
"math"
"reflect"
"strconv"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
)
// JSONPb is a Marshaler which marshals/unmarshals into/from JSON
@@ -30,6 +32,21 @@ func (*JSONPb) ContentType(_ interface{}) string {
// Marshal marshals "v" into JSON.
func (j *JSONPb) Marshal(v interface{}) ([]byte, error) {
if p, ok := v.(proto.Message); ok {
// protojson already returns a freshly allocated slice that the caller owns, so
// routing it through a bytes.Buffer only added an allocation and a copy of the
// whole message per call. Every unary response goes through here.
//
// The error is returned with a nil slice rather than whatever protojson produced
// alongside it, matching what the bytes.Buffer path did: marshalTo returned before
// writing anything, so a failed Marshal never handed back partial output.
b, err := j.MarshalOptions.Marshal(p)
if err != nil {
return nil, err
}
return b, nil
}
var buf bytes.Buffer
if err := j.marshalTo(&buf, v); err != nil {
return nil, err
@@ -251,18 +268,36 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions
return fmt.Errorf("unsupported type of map field key: %v", rv.Type().Key())
}
m := make(map[string]*json.RawMessage)
if err := d.Decode(&m); err != nil {
var raw json.RawMessage
if err := d.Decode(&raw); err != nil {
return err
}
m := make(map[string]*json.RawMessage)
if err := json.Unmarshal(raw, &m); err != nil {
return err
}
// encoding/json keeps the last value of a repeated key, while protojson
// rejects a duplicate map key, also when two spellings convert to the
// same key (e.g. "1" and "01"). Reject both here too.
if k, ok := duplicateObjectKey(raw); ok {
return fmt.Errorf("duplicate map key %q", k)
}
seen := make(map[any]struct{}, len(m))
for k, v := range m {
result := conv.Call([]reflect.Value{reflect.ValueOf(k)})
if err := result[1].Interface(); err != nil {
return err.(error)
}
bk := result[0]
if _, ok := seen[bk.Interface()]; ok {
return fmt.Errorf("duplicate map key %q", k)
}
seen[bk.Interface()] = struct{}{}
bv := reflect.New(rv.Type().Elem())
if v == nil {
if err := rejectNullEnumItem(rv.Type().Elem()); err != nil {
return err
}
null := json.RawMessage("null")
v = &null
}
@@ -293,6 +328,11 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions
rv.Set(reflect.MakeSlice(rv.Type(), 0, 0))
}
for _, item := range sl {
if string(item) == "null" {
if err := rejectNullEnumItem(rv.Type().Elem()); err != nil {
return err
}
}
bv := reflect.New(rv.Type().Elem())
if err := unmarshalJSONPb([]byte(item), unmarshaler, bv.Interface()); err != nil {
return err
@@ -308,11 +348,30 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions
}
switch v := repr.(type) {
case string:
// TODO(yugui) Should use proto.StructProperties?
// protojson writes enums by name, so accept the name here too.
if e, ok := rv.Interface().(protoreflect.Enum); ok {
if ev := e.Descriptor().Values().ByName(protoreflect.Name(v)); ev != nil {
rv.SetInt(int64(ev.Number()))
return nil
}
if unmarshaler.DiscardUnknown {
return nil
}
return fmt.Errorf("invalid value %q for enum %s", v, e.Descriptor().FullName())
}
return fmt.Errorf("unmarshaling of symbolic enum %q not supported: %T", repr, rv.Interface())
case float64:
// Enum values are int32 on the wire. A fractional or out-of-range
// number would otherwise be silently truncated/wrapped into a bogus
// enum here, unlike protojson which rejects it, so reject it too.
if v != math.Trunc(v) || v < math.MinInt32 || v > math.MaxInt32 {
return fmt.Errorf("%v is not a valid value for enum %T", repr, rv.Interface())
}
rv.Set(reflect.ValueOf(int32(v)).Convert(rv.Type()))
return nil
case nil:
// protojson leaves a null enum field unset.
return nil
default:
return fmt.Errorf("cannot assign %#v into Go type %T", repr, rv.Interface())
}
@@ -320,6 +379,43 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions
return d.Decode(v)
}
// rejectNullEnumItem returns an error when t is an enum other than
// google.protobuf.NullValue. protojson leaves a null enum field unset, but
// rejects null as a list item or map value of such an enum.
func rejectNullEnumItem(t reflect.Type) error {
e, ok := reflect.Zero(t).Interface().(protoreflect.Enum)
if !ok || e.Descriptor().FullName() == "google.protobuf.NullValue" {
return nil
}
return fmt.Errorf("invalid value null for enum %s", e.Descriptor().FullName())
}
// duplicateObjectKey returns the first key that appears more than once in the
// JSON object in data.
func duplicateObjectKey(data []byte) (string, bool) {
d := json.NewDecoder(bytes.NewReader(data))
if t, err := d.Token(); err != nil || t != json.Delim('{') {
return "", false
}
seen := make(map[string]struct{})
for d.More() {
t, err := d.Token()
if err != nil {
return "", false
}
k, _ := t.(string)
if _, ok := seen[k]; ok {
return k, true
}
seen[k] = struct{}{}
var v json.RawMessage
if err := d.Decode(&v); err != nil {
return "", false
}
}
return "", false
}
type protoEnum interface {
fmt.Stringer
EnumDescriptor() ([]byte, []int)
@@ -40,6 +40,13 @@ func (marshaller *ProtoMarshaller) NewDecoder(reader io.Reader) Decoder {
if err != nil {
return err
}
// ReadAll drains the reader, so a call with nothing left to read has
// to report io.EOF like the other decoders. Otherwise it decodes an
// empty message every time, and a loop decoding until io.EOF, such as
// the generated client streaming handlers, never terminates.
if len(buffer) == 0 {
return io.EOF
}
return marshaller.Unmarshal(buffer, value)
})
}
@@ -44,6 +44,18 @@ func MarshalerForRequest(mux *ServeMux, r *http.Request) (inbound Marshaler, out
}
for _, contentTypeVal := range r.Header[contentTypeHeader] {
// A header that is already exactly a registered media type -- "application/json",
// which is what clients send -- needs no parsing. mime.ParseMediaType allocates a
// parameter map even when the value carries no parameters, and it would return this
// value unchanged, so the lookup below would be the same one.
//
// This is also what the Accept loop above already does: the registry is keyed by the
// strings passed to WithMarshalerOption, and that loop matches the header value
// against them directly.
if m, ok := mux.marshalers.mimeMap[contentTypeVal]; ok {
inbound = m
break
}
contentType, _, err := mime.ParseMediaType(contentTypeVal)
if err != nil {
grpclog.Errorf("Failed to parse Content-Type %s: %v", contentTypeVal, err)
+132 -27
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"mime"
"net/http"
"net/textproto"
"regexp"
@@ -44,7 +45,9 @@ const (
UnescapingModeDefault = UnescapingModeLegacy
)
var encodedPathSplitter = regexp.MustCompile("(/|%2F)")
// Percent-encoding is case insensitive (RFC 3986, section 6.2.2.1), so an
// escaped path separator has to be recognized in either spelling.
var encodedPathSplitter = regexp.MustCompile("(/|%2[fF])")
// A HandlerFunc handles a specific pair of path pattern and HTTP method.
type HandlerFunc func(w http.ResponseWriter, r *http.Request, pathParams map[string]string)
@@ -75,6 +78,7 @@ type ServeMux struct {
unescapingMode UnescapingMode
writeContentLength bool
disableChunkedEncoding bool
strictDeepWildcard bool
}
// ServeMuxOption is an option that can be given to a ServeMux on construction.
@@ -137,6 +141,19 @@ func WithDisableChunkedEncoding() ServeMuxOption {
}
}
// WithStrictDeepWildcardMatching makes deep wildcards ("**") require at least
// one path segment when preceded by another segment. For example,
// "/v3/files/{path=**}" will not match "/v3/files". A trailing slash still
// provides an empty segment, so "/v3/files/" continues to match.
//
// This option applies to all patterns registered with the ServeMux, including
// generated routes and routes registered with HandlePath.
func WithStrictDeepWildcardMatching() ServeMuxOption {
return func(mux *ServeMux) {
mux.strictDeepWildcard = true
}
}
// SetQueryParameterParser sets the query parameter parser, used to populate message from query parameters.
// Configuring this will mean the generated OpenAPI output is no longer correct, and it should be
// done with careful consideration.
@@ -151,24 +168,55 @@ type HeaderMatcherFunc func(string) (string, bool)
// DefaultHeaderMatcher is used to pass http request headers to/from gRPC context. This adds permanent HTTP header
// keys (as specified by the IANA, e.g: Accept, Cookie, Host) to the gRPC metadata with the grpcgateway- prefix. If you want to know which headers are considered permanent, you can view the isPermanentHTTPHeader function.
// HTTP headers that start with 'Grpc-Metadata-' are mapped to gRPC metadata after removing the prefix 'Grpc-Metadata-'.
// Other headers are not added to the gRPC metadata.
//
// Earlier versions also mapped HTTP headers that start with 'Grpc-Metadata-' to gRPC metadata after removing the
// prefix. That let any HTTP client set an arbitrary metadata key, which a backend trusting a key as set by an
// interceptor or the gateway itself could not tell apart from the real value. Use LegacyHeaderMatcher, or the
// WithLegacyHeaderMatching option, to keep forwarding those headers.
func DefaultHeaderMatcher(key string) (string, bool) {
switch key = textproto.CanonicalMIMEHeaderKey(key); {
case isPermanentHTTPHeader(key):
if key = textproto.CanonicalMIMEHeaderKey(key); isPermanentHTTPHeader(key) {
return MetadataPrefix + key, true
case strings.HasPrefix(key, MetadataHeaderPrefix):
return key[len(MetadataHeaderPrefix):], true
}
return "", false
}
// LegacyHeaderMatcher is the incoming header matcher earlier releases used by default. In addition to the
// permanent HTTP headers DefaultHeaderMatcher maps, HTTP headers that start with 'Grpc-Metadata-' are mapped
// to gRPC metadata after removing the prefix 'Grpc-Metadata-'.
//
// This lets any HTTP client set any metadata key the backend reads, except the ones the gateway reserves for
// itself, so only use it when the backend does not trust a metadata key to have been set by the gateway.
func LegacyHeaderMatcher(key string) (string, bool) {
switch key = textproto.CanonicalMIMEHeaderKey(key); {
case isPermanentHTTPHeader(key):
return MetadataPrefix + key, true
case strings.HasPrefix(key, MetadataHeaderPrefix):
mdKey := key[len(MetadataHeaderPrefix):]
// The grpcgateway- namespace is reserved for permanent HTTP headers the
// gateway maps itself, so refuse to forward a Grpc-Metadata- header that
// strips into it. Otherwise Grpc-Metadata-grpcgateway-host lets a client
// inject a value indistinguishable from the gateway-set grpcgateway-host.
if strings.HasPrefix(strings.ToLower(mdKey), MetadataPrefix) {
return "", false
}
return mdKey, true
}
return "", false
}
// WithLegacyHeaderMatching returns a ServeMuxOption that restores LegacyHeaderMatcher as the incoming header
// matcher, so HTTP headers that start with 'Grpc-Metadata-' are forwarded as gRPC metadata again.
func WithLegacyHeaderMatching() ServeMuxOption {
return WithIncomingHeaderMatcher(LegacyHeaderMatcher)
}
func defaultOutgoingHeaderMatcher(key string) (string, bool) {
return fmt.Sprintf("%s%s", MetadataHeaderPrefix, key), true
return MetadataHeaderPrefix + key, true
}
func defaultOutgoingTrailerMatcher(key string) (string, bool) {
return fmt.Sprintf("%s%s", MetadataTrailerPrefix, key), true
return MetadataTrailerPrefix + key, true
}
// WithIncomingHeaderMatcher returns a ServeMuxOption representing a headerMatcher for incoming request to gateway.
@@ -376,15 +424,28 @@ func NewServeMux(opts ...ServeMuxOption) *ServeMux {
serveMux.outgoingTrailerMatcher = defaultOutgoingTrailerMatcher
}
// Options such as WithHealthEndpointAt register handlers while the options
// are still being applied, so they were wrapped with only the middlewares
// configured before them. Rewrap them now that all middlewares are known.
if len(serveMux.middlewares) > 0 {
chain := chainMiddlewares(serveMux.middlewares)
for _, handlers := range serveMux.handlers {
for i := range handlers {
handlers[i].h = chain(handlers[i].raw)
}
}
}
return serveMux
}
// Handle associates "h" to the pair of HTTP method and path pattern.
func (s *ServeMux) Handle(meth string, pat Pattern, h HandlerFunc) {
raw := h
if len(s.middlewares) > 0 {
h = chainMiddlewares(s.middlewares)(h)
}
s.handlers[meth] = append([]handler{{pat: pat, h: h}}, s.handlers[meth]...)
s.handlers[meth] = append([]handler{{pat: pat, h: h, raw: raw}}, s.handlers[meth]...)
}
// HandlePath allows users to configure custom path handlers.
@@ -415,11 +476,22 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
// TODO(v3): remove UnescapingModeLegacy
if s.unescapingMode != UnescapingModeLegacy && r.URL.RawPath != "" {
path = r.URL.RawPath
unescapingMode := s.unescapingMode
if unescapingMode != UnescapingModeLegacy {
if r.URL.RawPath != "" {
path = r.URL.RawPath
} else {
// net/url only sets RawPath when the request path is not in its
// default encoding. Without it, Path is all there is and it has
// already been unescaped once, so unescaping it again while matching
// would decode a sequence like %252F twice.
unescapingMode = UnescapingModeLegacy
}
}
if override := r.Header.Get("X-HTTP-Method-Override"); override != "" && !s.disableHTTPMethodOverride && s.isPathLengthFallback(r) {
// "X-Http-Method-Override" is the canonical spelling; Header.Get allocates a
// canonicalised copy of any other, and this lookup happens on every request.
if override := r.Header.Get("X-Http-Method-Override"); override != "" && !s.disableHTTPMethodOverride && s.isPathLengthFallback(r) {
if err := r.ParseForm(); err != nil {
_, outboundMarshaler := MarshalerForRequest(s, r)
sterr := status.Error(codes.InvalidArgument, err.Error())
@@ -434,7 +506,7 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// in this escaping mode we would be double unescaping but in UnescapingModeAllCharacters, we still do as the
// path is the RawPath (i.e. unescaped). That does mean that the behavior of this function will change its default
// behavior when the UnescapingModeDefault gets changed from UnescapingModeLegacy to UnescapingModeAllExceptReserved
if s.unescapingMode == UnescapingModeAllCharacters {
if unescapingMode == UnescapingModeAllCharacters {
pathComponents = encodedPathSplitter.Split(path[1:], -1)
} else {
pathComponents = strings.Split(path[1:], "/")
@@ -460,20 +532,33 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
idx = len(lastPathComponent) - len(patVerb) - 1
}
if idx == 0 {
_, outboundMarshaler := MarshalerForRequest(s, r)
s.routingErrorHandler(ctx, s, outboundMarshaler, w, r, http.StatusNotFound)
return
// The last component is the bare verb with nothing before it,
// which this pattern cannot match. Other patterns still might, so
// move on rather than ending the search with a 404.
continue
}
comps := make([]string, len(pathComponents))
copy(comps, pathComponents)
// Only copy the components when the verb has to be split off the last
// one. MatchAndEscape never mutates its input, so sharing the slice
// across handlers is safe, and copying it per handler otherwise costs
// len(pathComponents) allocations for every registered pattern.
comps := pathComponents
if idx > 0 {
comps = make([]string, len(pathComponents))
copy(comps, pathComponents)
comps[len(comps)-1], verb = lastPathComponent[:idx], lastPathComponent[idx+1:]
}
pathParams, err := h.pat.MatchAndEscape(comps, verb, s.unescapingMode)
pathParams, err := h.pat.matchAndEscape(comps, verb, unescapingMode, s.strictDeepWildcard)
if err != nil {
// ErrNotMatch is returned once for every registered pattern the request does not
// match, so it is by far the most common error reaching this branch. Checking it
// first keeps errors.As off that path: its target parameter is an any, so &mse is
// boxed onto the heap on every call -- one allocation per route a request did not
// match, which grows with the number of registered routes.
if errors.Is(err, ErrNotMatch) {
continue
}
var mse MalformedSequenceError
if ok := errors.As(err, &mse); ok {
_, outboundMarshaler := MarshalerForRequest(s, r)
@@ -495,11 +580,24 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Note we are not eagerly checking the request here as we want to return the
// right HTTP status code, and we need to process the fallback candidates in
// order to do that.
for m, handlers := range s.handlers {
// GET is tried first when the request is subject to path length fallback:
// map iteration order is random, and a match for another method would
// otherwise return 405 before the GET handler is reached.
methods := make([]string, 0, len(s.handlers))
if s.isPathLengthFallback(r) {
methods = append(methods, http.MethodGet)
}
for m := range s.handlers {
if m == http.MethodGet && s.isPathLengthFallback(r) {
continue
}
methods = append(methods, m)
}
for _, m := range methods {
if m == r.Method {
continue
}
for _, h := range handlers {
for _, h := range s.handlers[m] {
var verb string
patVerb := h.pat.Verb()
@@ -508,14 +606,14 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
idx = len(lastPathComponent) - len(patVerb) - 1
}
comps := make([]string, len(pathComponents))
copy(comps, pathComponents)
comps := pathComponents
if idx > 0 {
comps = make([]string, len(pathComponents))
copy(comps, pathComponents)
comps[len(comps)-1], verb = lastPathComponent[:idx], lastPathComponent[idx+1:]
}
pathParams, err := h.pat.MatchAndEscape(comps, verb, s.unescapingMode)
pathParams, err := h.pat.matchAndEscape(comps, verb, unescapingMode, s.strictDeepWildcard)
if err != nil {
var mse MalformedSequenceError
if ok := errors.As(err, &mse); ok {
@@ -558,12 +656,19 @@ func (s *ServeMux) GetForwardResponseOptions() []func(context.Context, http.Resp
}
func (s *ServeMux) isPathLengthFallback(r *http.Request) bool {
return !s.disablePathLengthFallback && r.Method == "POST" && r.Header.Get("Content-Type") == "application/x-www-form-urlencoded"
if s.disablePathLengthFallback || r.Method != http.MethodPost {
return false
}
// Like net/http's ParseForm, ignore parameters such as charset.
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
return err == nil && mediaType == "application/x-www-form-urlencoded"
}
type handler struct {
pat Pattern
h HandlerFunc
// raw is h before middlewares were applied.
raw HandlerFunc
}
func (s *ServeMux) handleHandler(h handler, w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
+83 -5
View File
@@ -26,6 +26,9 @@ func (e MalformedSequenceError) Error() string {
type op struct {
code utilities.OpCode
operand int
// multisegment is set on an OpPush that is one segment of a variable
// spanning several segments, such as the "*" in {name=shelves/*}.
multisegment bool
}
// Pattern is a template pattern of http request paths defined in
@@ -43,6 +46,20 @@ type Pattern struct {
tailLen int
// verb is the VERB part of the path pattern. It is empty if the pattern does not have VERB part.
verb string
// strictDeepWildcard makes a deep wildcard ("**") preceded by a segment require at least one
// remaining path component.
strictDeepWildcard bool
}
// PatternOpt configures optional behavior of a Pattern.
type PatternOpt func(*Pattern)
// WithStrictDeepWildcard makes a deep wildcard ("**") that is preceded by another
// segment refuse to match zero path segments. For example, "/v3/files/{path=**}"
// will not match "/v3/files". A bare "**" with nothing preceding it still matches
// zero segments. See https://github.com/grpc-ecosystem/grpc-gateway/issues/5771.
func WithStrictDeepWildcard() PatternOpt {
return func(p *Pattern) { p.strictDeepWildcard = true }
}
// NewPattern returns a new Pattern from the given definition values.
@@ -51,6 +68,12 @@ type Pattern struct {
// "version" must be 1 for now.
// It returns an error if the given definition is invalid.
func NewPattern(version int, ops []int, pool []string, verb string) (Pattern, error) {
return NewPatternWithOptions(version, ops, pool, verb)
}
// NewPatternWithOptions is like NewPattern but additionally accepts options that modify
// the matching behavior of the returned Pattern, e.g. WithStrictDeepWildcard.
func NewPatternWithOptions(version int, ops []int, pool []string, verb string, opts ...PatternOpt) (Pattern, error) {
if version != 1 {
grpclog.Errorf("unsupported version: %d", version)
return Pattern{}, ErrInvalidPattern
@@ -106,6 +129,15 @@ func NewPattern(version int, ops []int, pool []string, verb string) (Pattern, er
return Pattern{}, ErrInvalidPattern
}
stack++
// The segments of a variable are the ops pushed right before its
// OpConcatN, so these are the ones of a multi-segment variable.
if op.operand > 1 {
for j := len(typedOps) - op.operand; j < len(typedOps); j++ {
if typedOps[j].code == utilities.OpPush {
typedOps[j].multisegment = true
}
}
}
case utilities.OpCapture:
if op.operand < 0 || len(pool) <= op.operand {
grpclog.Errorf("variable name index out of bound: %d", op.operand)
@@ -129,14 +161,18 @@ func NewPattern(version int, ops []int, pool []string, verb string) (Pattern, er
}
typedOps = append(typedOps, op)
}
return Pattern{
pat := Pattern{
ops: typedOps,
pool: pool,
vars: vars,
stacksize: maxstack,
tailLen: tailLen,
verb: verb,
}, nil
}
for _, opt := range opts {
opt(&pat)
}
return pat, nil
}
// MustPattern is a helper function which makes it easier to call NewPattern in variable initialization.
@@ -152,6 +188,10 @@ func MustPattern(p Pattern, err error) Pattern {
// matched but contained malformed escape sequences. If successful, the function
// returns a mapping from field paths to their captured values.
func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode UnescapingMode) (map[string]string, error) {
return p.matchAndEscape(components, verb, unescapingMode, false)
}
func (p Pattern) matchAndEscape(components []string, verb string, unescapingMode UnescapingMode, strictDeepWildcard bool) (map[string]string, error) {
if p.verb != verb {
if p.verb != "" {
return nil, ErrNotMatch
@@ -165,8 +205,29 @@ func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode
}
var pos int
stack := make([]string, 0, p.stacksize)
captured := make([]string, len(p.vars))
// Scratch space for the match. Neither backing array escapes -- only the individual
// strings they hold are copied into the returned bindings -- so fixed-size arrays keep
// both off the heap for the patterns generated code registers, where the stack size and
// the variable count are single digits.
//
// This matters beyond one allocation each: ServeHTTP calls matchAndEscape once per
// registered pattern until one matches, and both allocations happened before the
// non-match return below, so a request paid for them once for every route it did not
// match. With a few dozen routes registered that was the largest single source of
// allocations in routing.
var stackArr, capturedArr [8]string
stack := stackArr[:0]
if p.stacksize > len(stackArr) {
stack = make([]string, 0, p.stacksize)
}
var captured []string
if n := len(p.vars); n <= len(capturedArr) {
captured = capturedArr[:n]
} else {
captured = make([]string, n)
}
l := len(components)
for _, op := range p.ops {
var err error
@@ -184,7 +245,14 @@ func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode
return nil, ErrNotMatch
}
} else if op.code == utilities.OpPush {
if c, err = unescape(c, unescapingMode, false); err != nil {
// google.api.http decodes a variable spanning several segments
// "except %2F and %2f", so a "*" in it can't add a path separator
// to the bound value. Other escapes are decoded as for {var}.
mode := unescapingMode
if op.multisegment && mode == UnescapingModeAllExceptReserved {
mode = UnescapingModeAllExceptSlash
}
if c, err = unescape(c, mode, op.multisegment); err != nil {
return nil, err
}
}
@@ -196,6 +264,16 @@ func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode
return nil, ErrNotMatch
}
end -= p.tailLen
if (p.strictDeepWildcard || strictDeepWildcard) && pos > 0 && pos == end {
// A deep wildcard ("**") is allowed to match zero path segments when it is
// the first thing being matched in the pattern (pos == 0). But once a literal
// or variable segment has already consumed a component, "**" needs the request
// path to continue past that segment — it cannot succeed with nothing left to
// consume at all (though an empty trailing segment, e.g. from a trailing slash,
// still counts as a real component and is fine).
// See https://github.com/grpc-ecosystem/grpc-gateway/issues/5771.
return nil, ErrNotMatch
}
c := strings.Join(components[pos:end], "/")
if c, err = unescape(c, unescapingMode, true); err != nil {
return nil, err
+145 -17
View File
@@ -4,7 +4,6 @@ import (
"errors"
"fmt"
"net/url"
"regexp"
"strconv"
"strings"
"time"
@@ -16,13 +15,41 @@ import (
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/emptypb"
field_mask "google.golang.org/protobuf/types/known/fieldmaskpb"
"google.golang.org/protobuf/types/known/structpb"
"google.golang.org/protobuf/types/known/timestamppb"
"google.golang.org/protobuf/types/known/wrapperspb"
)
var valuesKeyRegexp = regexp.MustCompile(`^(.*)\[(.*)\]$`)
// splitMapKey splits a query parameter name of the form "field[key]" into the part before the
// bracket and the key inside it, reporting whether the name has that shape at all.
//
// This replaces a FindStringSubmatch against `^(.*)\[(.*)\]$`, which ran for every query
// parameter and cost two allocations each -- the submatch slice and the backtracker's state --
// to answer a question that is two index operations. The returned strings are slices of the
// caller's key, so nothing is copied; the caller rebuilds "[key]" as key[len(prefix):] rather
// than concatenating it back together.
//
// The regexp is matched exactly, including two details worth spelling out:
//
// - The first group is greedy, so the bracket that counts is the last one before the final
// "]". "a[b]c]" splits into "a" and "b]c", which is what LastIndexByte over everything but
// the final byte finds.
// - Go's regexp does not let "." match a newline and anchors ^ and $ at the ends of the text,
// so a key containing a newline could never match the pattern no matter where the brackets
// sat. The explicit newline check keeps that, rather than quietly starting to treat
// "a\n[b]" as a map key.
func splitMapKey(key string) (prefix, inner string, ok bool) {
if len(key) < 2 || key[len(key)-1] != ']' || strings.IndexByte(key, '\n') >= 0 {
return "", "", false
}
open := strings.LastIndexByte(key[:len(key)-1], '[')
if open < 0 {
return "", "", false
}
return key[:open], key[open+1 : len(key)-1], true
}
var currentQueryParser QueryParameterParser = &DefaultQueryParser{}
@@ -44,30 +71,67 @@ func PopulateQueryParameters(msg proto.Message, values url.Values, filter *utili
type DefaultQueryParser struct{}
// Parse populates "values" into "msg".
// A value is ignored if its key starts with one of the elements in "filter".
// A value is ignored if its key starts with one of the elements in "filter",
// or names a field that contains one of them.
func (*DefaultQueryParser) Parse(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error {
// A field is addressable by both its proto name and its JSON name, so two
// keys can set the same one. Record which fields have been set and refuse a
// second key for a field, the way protojson refuses a duplicate field in a
// body, instead of letting map iteration order pick the value that survives.
seen := make(map[string]struct{}, len(values))
for key, values := range values {
if match := valuesKeyRegexp.FindStringSubmatch(key); len(match) == 3 {
key = match[1]
values = append([]string{match[2]}, values...)
fieldKey, mapKey := key, ""
if prefix, inner, ok := splitMapKey(key); ok {
fieldKey, mapKey = prefix, key[len(prefix):]
values = append([]string{inner}, values...)
}
msgValue := msg.ProtoReflect()
fieldPath := normalizeFieldPath(msgValue, strings.Split(key, "."))
if filter.HasCommonPrefix(fieldPath) {
fieldPath := normalizeFieldPath(msgValue, strings.Split(fieldKey, "."))
if filter.HasCommonPrefix(fieldPath) || containsFilteredField(filter, fieldPath) {
continue
}
if err := populateFieldValueFromPath(msgValue, fieldPath, values); err != nil {
field := strings.Join(fieldPath, ".") + mapKey
if _, ok := seen[field]; ok {
return fmt.Errorf("duplicate field %q", field)
}
seen[field] = struct{}{}
if err := populateFieldValueFromPath(msgValue, fieldPath, values, mapKey != ""); err != nil {
return err
}
}
return nil
}
// containsFilteredField reports whether fieldPath names a field that contains
// one of the sequences in filter, such as "id" for a path parameter bound to
// "id.value". Setting such a field from the query, which the parser can do for
// well-known types like wrappers and timestamps, would replace the whole
// message and with it the value already bound from the path or body.
func containsFilteredField(filter *utilities.DoubleArray, fieldPath []string) bool {
if len(filter.Base) == 0 {
return false
}
var i int
for _, t := range fieldPath {
code, ok := filter.Encoding[t]
if !ok {
return false
}
j := filter.Base[i] + code
if len(filter.Check) <= j || filter.Check[j] != i+1 {
return false
}
i = j
}
return true
}
// PopulateFieldFromPath sets a value in a nested Protobuf structure.
func PopulateFieldFromPath(msg proto.Message, fieldPathString string, value string) error {
fieldPath := strings.Split(fieldPathString, ".")
return populateFieldValueFromPath(msg.ProtoReflect(), fieldPath, []string{value})
return populateFieldValueFromPath(msg.ProtoReflect(), fieldPath, []string{value}, false)
}
func normalizeFieldPath(msgValue protoreflect.Message, fieldPath []string) []string {
@@ -102,7 +166,7 @@ func normalizeFieldPath(msgValue protoreflect.Message, fieldPath []string) []str
return newFieldPath
}
func populateFieldValueFromPath(msgValue protoreflect.Message, fieldPath []string, values []string) error {
func populateFieldValueFromPath(msgValue protoreflect.Message, fieldPath []string, values []string, hasMapKey bool) error {
if len(fieldPath) < 1 {
return errors.New("no field path")
}
@@ -149,6 +213,18 @@ func populateFieldValueFromPath(msgValue protoreflect.Message, fieldPath []strin
msgValue = msgValue.Mutable(fieldDescriptor).Message()
}
// A key using the map syntax (field[key]=value) must name a map field,
// or a repeated field of key/value messages laid out like map entries.
// Otherwise the bracket content would be bound as if it were a regular
// value: appended as a phantom element of a repeated field, or counted
// as a second value for a singular one.
if hasMapKey && !fieldDescriptor.IsMap() {
if isKeyValueList(fieldDescriptor) {
return populateKeyValueListField(fieldDescriptor, msgValue.Mutable(fieldDescriptor).List(), values)
}
return fmt.Errorf("field %q is not a map", fieldDescriptor.FullName().Name())
}
switch {
case fieldDescriptor.IsList():
return populateRepeatedField(fieldDescriptor, msgValue.Mutable(fieldDescriptor).List(), values)
@@ -205,6 +281,48 @@ func populateMapField(fieldDescriptor protoreflect.FieldDescriptor, mp protorefl
return nil
}
// isKeyValueList reports whether fieldDescriptor is a repeated message field
// whose message has exactly a singular "key" and a singular "value" field.
// Such a field is shaped like a map entry list, but can hold more than one
// value for a key.
func isKeyValueList(fieldDescriptor protoreflect.FieldDescriptor) bool {
if !fieldDescriptor.IsList() || fieldDescriptor.Message() == nil {
return false
}
fields := fieldDescriptor.Message().Fields()
if fields.Len() != 2 {
return false
}
key, value := fields.ByName("key"), fields.ByName("value")
return key != nil && key.Cardinality() != protoreflect.Repeated &&
value != nil && value.Cardinality() != protoreflect.Repeated
}
// populateKeyValueListField appends one key/value message to list for each of
// values[1:], all with the key values[0].
func populateKeyValueListField(fieldDescriptor protoreflect.FieldDescriptor, list protoreflect.List, values []string) error {
fields := fieldDescriptor.Message().Fields()
keyField, valueField := fields.ByName("key"), fields.ByName("value")
key, err := parseField(keyField, values[0])
if err != nil {
return fmt.Errorf("parsing map key %q: %w", fieldDescriptor.FullName().Name(), err)
}
for _, value := range values[1:] {
v, err := parseField(valueField, value)
if err != nil {
return fmt.Errorf("parsing map value %q: %w", fieldDescriptor.FullName().Name(), err)
}
entry := list.NewElement()
entry.Message().Set(keyField, key)
entry.Message().Set(valueField, v)
list.Append(entry)
}
return nil
}
func parseField(fieldDescriptor protoreflect.FieldDescriptor, value string) (protoreflect.Value, error) {
switch fieldDescriptor.Kind() {
case protoreflect.BoolKind:
@@ -224,7 +342,7 @@ func parseField(fieldDescriptor protoreflect.FieldDescriptor, value string) (pro
// Look for enum by name
v := enum.Descriptor().Values().ByName(protoreflect.Name(value))
if v == nil {
i, err := strconv.Atoi(value)
i, err := strconv.ParseInt(value, 10, 32)
if err != nil {
return protoreflect.Value{}, fmt.Errorf("%q is not a valid value", value)
}
@@ -259,13 +377,13 @@ func parseField(fieldDescriptor protoreflect.FieldDescriptor, value string) (pro
}
return protoreflect.ValueOfUint64(v), nil
case protoreflect.FloatKind:
v, err := strconv.ParseFloat(value, 32)
v, err := parseFloat(value, 32)
if err != nil {
return protoreflect.Value{}, err
}
return protoreflect.ValueOfFloat32(float32(v)), nil
case protoreflect.DoubleKind:
v, err := strconv.ParseFloat(value, 64)
v, err := parseFloat(value, 64)
if err != nil {
return protoreflect.Value{}, err
}
@@ -305,13 +423,13 @@ func parseMessage(msgDescriptor protoreflect.MessageDescriptor, value string) (p
}
msg = durationpb.New(d)
case "google.protobuf.DoubleValue":
v, err := strconv.ParseFloat(value, 64)
v, err := parseFloat(value, 64)
if err != nil {
return protoreflect.Value{}, err
}
msg = wrapperspb.Double(v)
case "google.protobuf.FloatValue":
v, err := strconv.ParseFloat(value, 32)
v, err := parseFloat(value, 32)
if err != nil {
return protoreflect.Value{}, err
}
@@ -356,7 +474,9 @@ func parseMessage(msgDescriptor protoreflect.MessageDescriptor, value string) (p
msg = wrapperspb.Bytes(v)
case "google.protobuf.FieldMask":
fm := &field_mask.FieldMask{}
fm.Paths = append(fm.Paths, strings.Split(value, ",")...)
if value != "" {
fm.Paths = append(fm.Paths, strings.Split(value, ",")...)
}
msg = fm
case "google.protobuf.Value":
var v structpb.Value
@@ -370,6 +490,14 @@ func parseMessage(msgDescriptor protoreflect.MessageDescriptor, value string) (p
return protoreflect.Value{}, err
}
msg = &v
case "google.protobuf.Empty":
// An Empty carries nothing, so the only thing the value can say is that the
// field is present. Accept the two spellings of "no content" and reject
// anything else, rather than silently ignoring it.
if value != "" && value != "{}" {
return protoreflect.Value{}, fmt.Errorf("expected an empty value or %q, got %q", "{}", value)
}
msg = &emptypb.Empty{}
default:
return protoreflect.Value{}, fmt.Errorf("unsupported message type: %q", string(msgDescriptor.FullName()))
}
+12 -4
View File
@@ -72,6 +72,7 @@ func (n node) children(seqs [][]int) []*node {
if lastVal == seqs[i][n.col+1] {
continue
}
lastVal = seqs[i][n.col+1]
last.right = i
last = &node{
row: i,
@@ -156,6 +157,11 @@ func (da *DoubleArray) HasCommonPrefix(seq []string) bool {
var i int
for _, t := range seq {
// A sequence ending at this node is already a prefix of seq, even if
// a longer sequence shares the path and the walk could carry on.
if da.hasTerminator(i) {
return true
}
code, ok := da.Encoding[t]
if !ok {
break
@@ -166,9 +172,11 @@ func (da *DoubleArray) HasCommonPrefix(seq []string) bool {
}
i = j
}
return da.hasTerminator(i)
}
// hasTerminator reports whether a sequence in the DoubleArray ends at node i.
func (da *DoubleArray) hasTerminator(i int) bool {
j := da.Base[i] + len(da.Encoding)
if len(da.Check) <= j || da.Check[j] != i+1 {
return false
}
return true
return j < len(da.Check) && da.Check[j] == i+1
}
+21 -1
View File
@@ -22,6 +22,26 @@ _testmain.go
*.exe
.envrc
/.testdb
# Per-checkout development state: this checkout's allocated TCP ports, the values derived from
# them, its decoded client certificates, and its own PostgreSQL/CockroachDB clusters. A git
# worktree is the native equivalent of a second devcontainer instance, so this is instance-local
# by definition -- never shared, never committed. See DEVELOPMENT.md.
/.dev/
# port-tamer writes this checkout's allocation to .dev/ports.env (the --state-file every task
# passes). These are where a bare `port-tamer` run at the repo root would put a stray second
# allocation instead; ignored so it cannot be committed by accident.
/.port-tamer.env
/.port-tamer.env.lock
# Personal, machine-local mise overrides (mise.toml IS committed/shared). Git has no knowledge of
# mise's conventions, so this must be ignored explicitly.
/mise.local.toml
# Provisioned on demand with `rake references:setup`; never committed.
/references/
.DS_Store
/.vscode
+15
View File
@@ -0,0 +1,15 @@
# Host dependencies only. Project tools and language runtimes belong in
# mise.toml; scripts/setup-host installs mise itself when necessary.
# Server and client binaries for the checkout-local test matrix.
brew "postgresql@14"
brew "postgresql@15"
brew "postgresql@16"
brew "postgresql@17"
brew "postgresql@18"
# mise compiles Ruby from source and links against these.
brew "openssl@3"
brew "readline"
brew "libyaml"
brew "gmp"
Loaded 100 of 723 files, more files were not shown because too many files have changed in this diff. Show more