Compare commits

...

352 Commits

Author SHA1 Message Date
Bai
4b29928d9b refactor: build asset tree and perm tree, do not need add node_key into assets_asset_nodes table 2025-12-14 12:08:20 +08:00
Bai
21cf94493c refactor: build asset tree and perm tree, do not need add node_key into assets_asset_nodes table 2025-12-14 10:32:22 +08:00
Bai
39caee6a2b refactor: add build asset tree test script for x build add cache: 0.001ms 2025-12-14 03:18:15 +08:00
Bai
9c1a36c573 refactor: add build user perm tree test script for x build add cache 2025-12-14 02:46:58 +08:00
Bai
5ca5234274 refactor: add build user perm tree test script for x build 2025-12-14 02:14:19 +08:00
Bai
83b7ccf225 refactor: add build user perm tree test script and log: finished 2025-12-13 22:08:17 +08:00
Bai
8ee3f9935a refactor: add build user perm tree test script and log 2025-12-13 18:46:53 +08:00
Bai
6ec0bee77d refactor: add build user perm tree test script and log 2025-12-13 18:16:45 +08:00
Bai
afd1cd4542 refactor: add build user perm tree test script and log 2025-12-13 15:05:15 +08:00
Bai
7c39f9f43e refactor: add build user perm tree test script and log 2025-12-13 14:14:37 +08:00
Bai
ab9e10791b refactor: add build user perm tree test script 2025-12-13 13:21:22 +08:00
Bai
878974ffbd refactor: add build asset tree test script 2025-12-13 12:04:32 +08:00
Bai
3052c5055f refactor: add build asset tree test script 2025-12-13 12:02:20 +08:00
Bai
4be301c2dc refactor: add build asset tree test script 2025-12-13 11:57:14 +08:00
Bai
7f90027754 refactor: finished through migrations and add fake generate through data 2025-12-13 10:41:15 +08:00
Bai
db3cd0bcc7 refactor: finished through migrations and add fake generate through data 2025-12-13 10:40:27 +08:00
Bai
6995754fd9 refactor: migrate assets_asset_nodes table add node_key field 2025-12-12 21:32:41 +08:00
Bai
8bd116e955 refactor: use 1 sql query 1 node assets_amount(exactly) 2025-12-12 21:30:11 +08:00
Bai
41884d054d refactor: add query_3_result demo can select raw sql 2025-12-11 19:31:53 +08:00
Bai
0ef78fb545 refactor: add query_3_result demo 2025-12-11 19:18:41 +08:00
Bai
98218e814b refactor: support cache_tree by ttl 2025-12-10 18:05:45 +08:00
Bai
167267067f refactor: support method get_node_all_assets, get_node_children(with_assets) 2025-12-10 14:22:08 +08:00
Bai
8126d52a8b refactor: generate complete perm tree; refactor compute nodes assets amount algorithm; 2025-12-10 13:06:42 +08:00
Bai
8b53a21659 refactor: finished generate user perm tree (include comupte node assets amount) 2025-12-09 19:41:40 +08:00
Bai
3496a31e1f refactor: finished generate user perm tree (only nodes) 2025-12-09 18:18:18 +08:00
Bai
2ec71feafc perf: rbac oauth2_provider perms i18n 2025-12-09 10:17:34 +08:00
Bai
02e8905330 perf: redirect/confirm page and i18n 2025-12-08 18:43:04 +08:00
Bai
8d68f5589b perf: redirect/confirm page and i18n 2025-12-08 18:43:04 +08:00
Bai
4df13fc384 perf: redirect/confirm page and i18n 2025-12-08 18:40:12 +08:00
Bai
78c1162028 perf: when DEBUG_DEV=True, allow OAUTH2_PROVIDER redirect_url localhost listen 2025-12-08 16:42:07 +08:00
Bai
14c2512b45 fix: accesskey authentication user is None error 2025-12-08 15:06:47 +08:00
Bai
d6d7072da5 perf: request.GET.copy() to dict(), because copy() returned values is list [] 2025-12-08 12:50:49 +08:00
fit2bot
993bc36c5e perf: handling the next parameter propagation issue in third-party authentication flows (#16395)
* perf: remove call client old- method via ?next=client

* feat: add 2 decorators for login-get and login-callback-get to set next_page and get next_page from session

* perf: code style

* perf: handling the next parameter propagation issue in third-party authentication flows

* perf: request.GET.dict() to copy()

* perf: style import

---------

Co-authored-by: Bai <baijiangjie@gmail.com>
2025-12-08 12:34:32 +08:00
fit2bot
ecff2ea07e perf: move oauth2_provider api auth_backend to the end, and while accesstoken_backend not user do not raise execption, go on next bakcned auth (#16393)
* perf: move oauth2_provider api auth_backend to the end, and while accesstoken_backend not user do not raise execption, go on next bakcned auth

* perf: re-sorted DEFAULT_AUTHENTICATION_CLASSES

---------

Co-authored-by: Bai <baijiangjie@gmail.com>
2025-12-08 09:57:17 +08:00
fit2bot
ba70edf221 perf: when oauth2 application delete expired well-known page cache via post_delete signal (#16392)
Co-authored-by: Bai <baijiangjie@gmail.com>
2025-12-08 09:54:18 +08:00
Bai
50050dff57 fix: cas only allow exist user login 2025-12-04 18:37:54 +08:00
jiangweidong
944226866c perf: Add a diff field to operate-log export 2025-12-04 18:01:01 +08:00
fit2bot
fe13221d88 fix: Improve server URI validation and connection testing in LDAP module (#16377)
Co-authored-by: wangruidong <940853815@qq.com>
2025-12-04 17:59:01 +08:00
fit2bot
ba17863892 perf: Remove unused CAS user exception handling and simplify login view error response (#16380)
* perf: Remove unused CAS user exception handling and simplify login view error response

* perf: position code

---------

Co-authored-by: wangruidong <940853815@qq.com>
Co-authored-by: Bai <baijiangjie@gmail.com>
2025-12-04 17:49:58 +08:00
fit2bot
065bfeda52 fix: only exists user login maybe invalid (#16379)
* fix: only exists user login maybe invalid

* fix: only exists user login maybe invalid

* fix: only exists user login maybe invalid

---------

Co-authored-by: Bai <baijiangjie@gmail.com>
2025-12-04 16:18:47 +08:00
wangruidong
04af26500a fix: Allow login with username or email for existing users 2025-12-04 10:04:32 +08:00
fit2bot
e0388364c3 fix: use third part authentication service rediect to client failed (#16370)
* perf: .well-known cached 1h and support saml2 redirect_to client

* fix: support wecom redirect_to client (reslove wecom waf 501 error)

* fix: support oauth2 auth rediect to client

* fix: safe next url

---------

Co-authored-by: Bai <baijiangjie@gmail.com>
2025-12-03 19:07:00 +08:00
Bai
3c96480b0c perf: add manage.py command: init_oauth2_provider, resolve init jumpserver client failed issue 2025-12-03 14:37:20 +08:00
Bai
95331a0c4b perf: redirect to client show tips 2025-12-02 18:39:48 +08:00
Bai
b8ecb703cf perf: url revoke_token/ to revoke/ 2025-12-02 18:21:13 +08:00
Bai
1a3f5e3f9a perf: default access token/refresh token expired at 1h/7day 2025-12-02 15:34:55 +08:00
Bai
854396e8d5 perf: access-token api 2025-12-02 15:25:55 +08:00
Bai
ab08603e66 perf: organize oauth2_provider urls, add .well-known API 2025-12-02 14:55:09 +08:00
Bai
427fd3f72c perf: organize oauth2_provider urls, add .well-known API 2025-12-02 14:55:09 +08:00
Bai
0aba9ba120 perf: hide the unused URLs in OAuth2 provider 2025-12-02 14:55:09 +08:00
Bai
045ca8807a feat: modify client redirect url 2025-12-01 19:04:19 +08:00
Bai
19a68d8930 feat: add api access token 2025-12-01 17:55:08 +08:00
Bai
75ed02a2d2 feat: add oauth2 provider accesstokens api 2025-12-01 17:55:08 +08:00
fit2bot
f420dac49c feat: Host cloud sync supports state cloud - i18n (#16304)
Co-authored-by: jiangweidong <1053570670@qq.com>
Co-authored-by: Jiangjie Bai <jiangjie.bai@fit2cloud.com>
2025-12-01 10:56:14 +08:00
Bai
1ee68134f2 fix: rename utils methond 2025-12-01 10:41:14 +08:00
Bai
937265db5d perf: add period task clear oauth2 provider expired tokens 2025-12-01 10:41:14 +08:00
Bai
c611d5e88b perf: add utils delete oauth2 provider application 2025-12-01 10:41:14 +08:00
Bai
883b6b6383 perf: skip_authorization for redirect to jms client 2025-12-01 10:41:14 +08:00
Bai
ac4c72064f perf: register jumpserver client logic 2025-12-01 10:41:14 +08:00
Bai
dbf8360e27 feat: add OAUTH2_PROVIDER_ACCESS_TOKEN_EXPIRE_SECONDS 2025-12-01 10:41:14 +08:00
github-actions[bot]
150d7a09bc perf: Update Dockerfile with new base image tag 2025-11-28 16:28:23 +08:00
Bai
a7ed20e059 perf: support as oauth2 provider 2025-11-28 16:28:23 +08:00
github-actions[bot]
1b7b8e6f2e perf: Update Dockerfile with new base image tag 2025-11-28 16:28:23 +08:00
Bai
cd22fbce19 perf: support as oauth2 provider 2025-11-28 16:28:23 +08:00
老广
c191d86f43 Refactor GitHub Actions workflow for event handling 2025-11-27 14:27:27 +08:00
wangruidong
7911137ffb fix: Truncate asset URL to 128 characters to prevent exceeding length limit 2025-11-27 14:17:19 +08:00
wangruidong
1053933cae fix: Add migration to refresh PostgreSQL collation version 2025-11-27 14:16:44 +08:00
wangruidong
96fdc025cd fix: Search for risk_level, search result is empty 2025-11-26 18:07:20 +08:00
wangruidong
fde19764e0 fix: Processing redirection url unquote 2025-11-25 14:00:31 +08:00
wangruidong
978fbc70e6 perf: Improve city retrieval fallback to handle missing values 2025-11-25 13:59:48 +08:00
Ewall555
636ffd786d feat: add namespace setting to k8s protocol configuration 2025-11-25 11:08:23 +08:00
feng
3b756aa26f perf: Component i18n lang lower 2025-11-25 10:56:37 +08:00
Bai
817c0099d1 perf: client pkg rename 2025-11-21 18:45:49 +08:00
Bai
a0d7871130 perf: client pkg rename 2025-11-21 18:45:49 +08:00
Bai
c97124c279 perf: client pkg rename 2025-11-20 17:59:22 +08:00
Bai
32a766ed34 perf: client pkg rename 2025-11-20 17:59:22 +08:00
Bai
58fd15d743 perf: client pkg rename 2025-11-20 17:59:22 +08:00
feng
f50250dedb perf: Client version 2025-11-20 16:37:23 +08:00
wangruidong
9e150b7fbe fix: One login lock, resulting in two logs 2025-11-20 15:01:06 +08:00
wangruidong
16c79f59a7 fix: Handle case where all time_periods have empty values as a selection of all 2025-11-20 11:31:09 +08:00
wangruidong
be0f04862a fix: Correctly pass runas value in ACL check for job execution 2025-11-19 19:08:29 +08:00
feng
1a3fb2f0db perf: Account bulk error prompt 2025-11-19 17:42:39 +08:00
Eric
4cd70efe66 perf: fix mp4 type replay 2025-11-19 17:10:26 +08:00
wangruidong
28700c01c8 perf: The login log records the locked login log 2025-11-19 17:08:55 +08:00
wangruidong
4524822245 fix: Solve this version of Mysql doesn't yet support 'LIMIT & IN/ALL/ANY/S0ME subquery' error 2025-11-19 09:52:05 +08:00
Eric
9d04fda018 perf: add match perm to user for suggestions api 2025-11-19 09:48:31 +08:00
老广
01c277cd1e Add Client to JumpServer components list 2025-11-19 09:19:52 +08:00
wangruidong
c4b3531d72 fix: correct handling of changed field values in operate log 2025-11-18 10:32:49 +08:00
feng
8870d1ef9e perf: Translate 2025-11-17 18:25:40 +08:00
wangruidong
6c5086a083 perf: implement login asset ACL checks in Job and JobExecution viewsets 2025-11-17 10:53:22 +08:00
wrd
e9f762a982 Revert "perf: Reduce the number of pub sub processing threads (#16072)"
This reverts commit 70068c9253.
2025-11-17 10:52:16 +08:00
wangruidong
d4d4cadbcd fix: OAuth2 Only allow existing users to log in operate log error 2025-11-13 18:42:28 +08:00
fit2bot
5e56590405 perf: change base img (#16279)
* perf: change base img

* perf: add gcc

* perf: change base image

* perf: Update Dockerfile with new base image tag

---------

Co-authored-by: ibuler <ibuler@qq.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-13 17:32:51 +08:00
wangruidong
ad8c0f6664 fix: SAML2 Only allow existing users to log in operate log error 2025-11-13 16:36:58 +08:00
wangruidong
47dd6babfc perf: add id verbose_name 2025-11-13 15:17:14 +08:00
ibuler
691d1c4dba perf: remove client key 2025-11-13 14:36:40 +08:00
ibuler
ac485804d5 perf: postgresql support ssl 2025-11-13 14:36:40 +08:00
ibuler
51e5fdb301 perf: change i18n 2025-11-13 10:05:37 +08:00
feng
69c4d613f7 perf: Add client support version 2025-11-11 16:37:12 +08:00
github-actions[bot]
1ad825bf0d perf: Update Dockerfile with new base image tag 2025-11-11 15:11:51 +08:00
ibuler
a286cb9343 deps: upgrade playwright 2025-11-11 15:11:51 +08:00
ibuler
1eb489bb2d perf: upgrade pg client 2025-11-11 14:24:53 +08:00
fit2bot
4334ae9e5e perf: update apt source config (#16265)
* perf: upgrade os to trixie

* perf: update apt source config

* perf: Update Dockerfile with new base image tag

---------

Co-authored-by: ibuler <ibuler@qq.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-11 14:17:35 +08:00
fit2bot
f2e346a0c3 perf: upgrade os to trixie (#16263)
* perf: upgrade os to trixie

* perf: Update Dockerfile with new base image tag

---------

Co-authored-by: ibuler <ibuler@qq.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-11 11:52:17 +08:00
wangruidong
dc20b06431 fix: i18n error 2025-11-10 18:14:18 +08:00
fit2bot
387a9248fc perf: Add a key to cover all protocols and ports (#16227)
Co-authored-by: wangruidong <940853815@qq.com>
2025-11-10 18:04:00 +08:00
wangruidong
705fd6385f fix: i18n error 2025-11-10 18:03:51 +08:00
fit2bot
0ccf36621f perf: Translate select files (#16212)
Co-authored-by: wangruidong <940853815@qq.com>
2025-11-06 18:26:54 +08:00
fit2bot
a9ae12fc2c perf: Implement data masking rules ACL check before job execution (#16216)
* perf: Implement data masking rules ACL check before job execution

* perf: Add login asset ACL check during job creation

* perf: Remove unused code.

---------

Co-authored-by: wangruidong <940853815@qq.com>
2025-11-06 18:25:34 +08:00
老广
7b1a25adde Add issue spam configuration file 2025-11-06 18:13:42 +08:00
feng
a1b5eb1cd8 perf: Translate 2025-11-06 15:50:15 +08:00
wangruidong
24ac642c5e fix: Escape percentage signs in gateway password for sshpass command 2025-11-06 14:10:24 +08:00
wangruidong
e4f5e21219 perf: Support batch import of leak passwords 2025-11-06 14:09:09 +08:00
feng
a2aae9db47 perf: Translate 2025-11-05 19:07:48 +08:00
feng
206c43cf75 fix: Fixed the issue of inaccurate calculation of the number of dashboard commands. 2025-11-04 18:14:02 +08:00
feng
019a657ec3 perf: Ssotoken login create operator choose org_id 2025-11-03 17:36:04 +08:00
feng
fad60ee40f perf: Translate 2025-11-03 10:51:22 +08:00
feng
1728412793 perf: Bulk account support node 2025-10-31 17:19:48 +08:00
feng
3e93034fbc perf: Update remote_client 2025-10-30 10:12:40 +08:00
feng
f4b3a7d73a perf: Sync feishu info 2025-10-29 14:53:45 +08:00
wrd
3781c40179 Revert "perf: update fields serialization and bump django and djangorestframe…"
This reverts commit dd0cacb4bc.
2025-10-29 11:19:50 +08:00
ibuler
fab6219cea perf: branches auto cleanup 2025-10-29 10:10:21 +08:00
fit2bot
dd0cacb4bc perf: update fields serialization and bump django and djangorestframework versions (#16209)
Co-authored-by: wangruidong <940853815@qq.com>
2025-10-28 16:42:06 +08:00
ibuler
b8639601a1 perf: branches auto cleanup 2025-10-27 15:33:06 +08:00
老广
ab9882c9c1 perf: check api summary 2025-10-27 15:28:21 +08:00
ibuler
77a7b74b15 perf: print summary in the end 2025-10-27 15:26:04 +08:00
dependabot[bot]
4bc05865f1 chore(deps): bump python-ldap from 3.4.3 to 3.4.5
Bumps [python-ldap](https://github.com/python-ldap/python-ldap) from 3.4.3 to 3.4.5.
- [Release notes](https://github.com/python-ldap/python-ldap/releases)
- [Changelog](https://github.com/python-ldap/python-ldap/blob/python-ldap-3.4.5/CHANGES)
- [Commits](https://github.com/python-ldap/python-ldap/compare/python-ldap-3.4.3...python-ldap-3.4.5)

---
updated-dependencies:
- dependency-name: python-ldap
  dependency-version: 3.4.5
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-10-27 15:24:06 +08:00
fit2bot
bec9e4f3a7 perf: update deps kombu (#16133)
* perf: update deps kombu

* perf: Update Dockerfile with new base image tag

---------

Co-authored-by: Ewall555 <a03216@foxmail.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: wrd <940853815@qq.com>
2025-10-27 15:18:16 +08:00
fit2bot
359adf3dbb perf: add check api for common user 2025-10-27 14:54:02 +08:00
feng
ac54bb672c fix: Bulk account invalid secret_reset 2025-10-24 18:18:16 +08:00
ibuler
9e3ba00bc4 perf: search support keyword q=str to search 2025-10-24 10:22:49 +08:00
wangruidong
2ec9a43317 fix: Any change to the LDAP server URI should require re-authentication and explicit re-entry of
the bind password, not reuse stored credentials
2025-10-23 15:29:47 +08:00
wangruidong
06be56ef06 fix: Enhance state check to include query parameter for session validation 2025-10-23 14:41:50 +08:00
ibuler
b2a618b206 perf: user sugguestion limit and serializer 2025-10-23 14:40:37 +08:00
wangruidong
1039c2e320 perf: ws/ldap perms check 2025-10-23 14:26:24 +08:00
fit2bot
8d7267400d fix: OpenID Only allow existing users to log in operate log error (#16013)
Co-authored-by: wangruidong <940853815@qq.com>
2025-10-22 14:53:12 +08:00
ibuler
d67e473884 perf: add auto cleanup branches 2025-10-22 11:46:09 +08:00
fit2bot
70068c9253 perf: Reduce the number of pub sub processing threads (#16072)
* perf: Reduce the number of pub sub processing threads

* perf: Using thread pool to process messages

---------

Co-authored-by: wangruidong <940853815@qq.com>
2025-10-21 17:41:14 +08:00
wangruidong
d68babb2e1 fix: Using winrm protocol to transfer files did not create a directory problem 2025-10-21 17:31:41 +08:00
wangruidong
afb6f466d5 perf: AppletHost translate 2025-10-21 17:31:03 +08:00
ibuler
453ad331ee perf: token retrieve 2025-10-21 10:48:08 +08:00
feng
d309d11a8f perf: Command count 2025-10-16 17:11:42 +08:00
feng
4771693a56 fix: dashboard command count 2025-10-16 16:25:01 +08:00
Chenyang Shen
cefc820ac1 Merge pull request #16163 from jumpserver/pr@dev@asset_acl_filter
perf: Asset acl filter action
2025-10-16 15:25:38 +08:00
feng
d007afdb43 perf: Asset acl filter action 2025-10-16 15:21:32 +08:00
feng
e8921a43be perf: Translate 2025-10-16 14:32:59 +08:00
wangruidong
a9b44103d4 fix: Handle email sending failure with appropriate error response 2025-10-16 11:28:41 +08:00
jiangweidong
4abf2bded6 perf: oracle cdb mode, common users need to start username with C## 2025-10-16 09:57:54 +08:00
feng
54693089a0 perf: replace command objects 2025-10-15 19:32:14 +08:00
Aaron3S
0b859dd502 feat: update i18n 2025-10-15 19:17:44 +08:00
feng
3fb27f969a perf: datamaskingrule perm 2025-10-15 17:33:27 +08:00
Aaron3S
45627a1d92 feat: update data masking rule filter 2025-10-15 16:51:58 +08:00
feng
245e2dab66 perf: Filter effective 2025-10-15 16:51:32 +08:00
Aaron3S
8f0a41b1a8 fix: fix data masking org problem 2025-10-15 15:51:14 +08:00
feng
1a9e56c520 perf: Translate 2025-10-15 15:24:19 +08:00
feng
67c2f471b4 perf: oracle sqlserver db2 dameng clickhouse redis db_name allow_blank 2025-10-15 11:30:00 +08:00
github-actions[bot]
b04f96f5f2 perf: Update Dockerfile with new base image tag 2025-10-14 18:09:25 +08:00
Eric
30f03b7d89 perf: change python base
perf: update deps
2025-10-14 18:09:25 +08:00
wangruidong
28a97d0b5a fix: Incorrect language display in some email content 2025-10-14 18:08:21 +08:00
Eric
3410686690 perf: fix python base ci 2025-10-14 17:47:31 +08:00
Eric
6860e2327f perf: add python base ci build 2025-10-14 17:41:05 +08:00
feng
20253e760c perf: translate 2025-10-14 17:13:42 +08:00
Aaron3S
a63cfde8d2 feat: add translate 2025-10-14 16:03:38 +08:00
feng
92e250e03b perf: user_can_authenticate add logger 2025-10-14 15:48:47 +08:00
wangruidong
098f0950cb fix: Incorrect language display in email content 2025-10-14 15:33:04 +08:00
feng
39b0830a6b perf: web script default [] 2025-10-14 13:59:11 +08:00
wangruidong
2e847bc2bc fix: Error in updating message subscription 500 2025-10-14 10:14:50 +08:00
wangruidong
f82f31876a fix: Mysql has set a gateway, and the command execution failed. 2025-10-14 10:14:23 +08:00
github-actions[bot]
cde182c015 perf: Update Dockerfile with new base image tag 2025-10-10 17:06:14 +08:00
Eric
b990cdf561 perf: update deps 2025-10-10 17:06:14 +08:00
feng
c9a062823d perf: Translate 2025-10-10 17:02:30 +08:00
feng
643ba4fc15 fix: Asset web script dont create 2025-10-10 11:43:11 +08:00
feng
d16a55bbe2 perf: Ticket details cannot view assets from other organizations. 2025-10-09 18:41:25 +08:00
fit2bot
ae31554729 perf: AppletHostOnly label match (#16109)
Co-authored-by: wangruidong <940853815@qq.com>
2025-10-09 18:13:37 +08:00
github-actions[bot]
53b47980a2 perf: Update Dockerfile with new base image tag 2025-10-09 16:55:50 +08:00
Eric
d31b5ee570 perf: update Dockerfile-base 2025-10-09 16:55:50 +08:00
feng
65aea1ea36 perf: Push account and change secret support gid 2025-10-09 16:39:32 +08:00
feng
5abb5c5d5a perf: Themes deep blue 2025-10-09 15:36:14 +08:00
feng
93e41a5004 perf: Luna themes default 2025-10-09 15:02:37 +08:00
feng
95f51bbe48 perf: Perference add themes 2025-10-09 14:47:11 +08:00
feng
0184d292ec perf: MFA code 2025-10-09 14:29:08 +08:00
fit2bot
23a6d320c7 feat: update i18n (#16101)
* feat: data masking

* feat: update i18n

---------

Co-authored-by: Aaron3S <chenyang@fit2cloud.com>
Co-authored-by: 老广 <ibuler@qq.com>
2025-10-09 10:03:11 +08:00
Aaron3S
b16304c48a feat: data masking 2025-10-09 09:59:23 +08:00
Gerry.tan
7cd1e4d3a0 perf: Dynamically configure the validity period of the email verification code 2025-09-28 11:26:32 +08:00
Eric
64a9987c3f perf: update rdp params 2025-09-28 11:20:52 +08:00
feng
18bfe312fa perf: open web ui 2025-09-25 15:49:10 +08:00
wangruidong
c593f91d77 fix: Account backup: when sending to the mailbox fails, the task status also shows the success problem. 2025-09-18 15:44:35 +08:00
feng
46da05652a fix: Fixed the issue where the final connection verification failed when the domain name contains . 2025-09-18 14:08:00 +08:00
feng
9249aba1a9 perf: Video player version 2025-09-18 11:03:58 +08:00
fit2bot
eca637c120 perf: Translate msg template (#16050)
* fix: Correct translation for device and user limits in django.po

* perf: Translate msg template

---------

Co-authored-by: wangruidong <940853815@qq.com>
2025-09-17 19:04:06 +08:00
feng
ddacd5fce1 fix: Ticket direct approval 2025-09-17 18:58:16 +08:00
wangruidong
3ca5c04099 fix: Add ignore_https_errors option to browser context 2025-09-17 16:30:54 +08:00
wangruidong
6603a073ec fix: Case 2025-09-17 15:32:23 +08:00
wangruidong
d745f7495a fix: Conflict 2025-09-17 15:32:23 +08:00
wangruidong
76f1667c89 perf: Restore msg template default value config 2025-09-17 15:32:23 +08:00
wangruidong
1ab1954299 fix: reset password msg error 2025-09-17 15:32:23 +08:00
wangruidong
c8335999a4 perf: Translate msg template 2025-09-17 15:32:23 +08:00
feng
5b4a67362d perf: Translate 2025-09-17 15:10:54 +08:00
fit2bot
e025073da2 fix: The number of exported data is incorrect (#16043)
Co-authored-by: wangruidong <940853815@qq.com>
2025-09-16 18:52:24 +08:00
feng
2155bc6862 perf: Migrate 2025-09-16 16:46:30 +08:00
wangruidong
953b515817 perf: Add is_alive filter to TerminalFilterSet 2025-09-16 16:30:57 +08:00
ibuler
7f7a354b2d fix: get obj error on queryset limit 2025-09-16 16:28:54 +08:00
Eric
2b2f7ea3f0 perf: add rdp true color 24 bit 2025-09-16 16:28:14 +08:00
feng
529123e1b5 perf: Translate 2025-09-16 16:15:09 +08:00
ibuler
e156ab6ad8 fix: force page limit 2025-09-16 13:48:06 +08:00
wangruidong
3c1fd134ae fix: There is something wrong with the format of the site message 2025-09-16 13:33:43 +08:00
Bai
b15f663c87 fix: AK/SK remained valid after the user expired. 2025-09-16 13:32:25 +08:00
wangruidong
93906dff0a fix: Export report pdf failed 2025-09-16 11:36:42 +08:00
Bai
307befdacd fix: login acl action reject > reviewers 500 2025-09-16 11:17:42 +08:00
feng626
dbfc4d3981 Revert "perf: User acl 500"
This reverts commit 849edd33c1.
2025-09-16 11:15:51 +08:00
feng
849edd33c1 perf: User acl 500 2025-09-16 10:50:41 +08:00
feng
37cceec8fe perf: get protocols error 500 2025-09-16 10:40:42 +08:00
feng
d2494c25cc perf: Translate 2025-09-15 19:19:01 +08:00
feng
023952582e fix: Push account failed 2025-09-15 15:32:27 +08:00
halo
863fe95100 perf: client version 2025-09-12 18:53:16 +08:00
wangruidong
4b0bdb18c9 perf: Template msg example error 2025-09-12 18:47:47 +08:00
Eric
10da053a95 perf: change applet-hosts view default limit 2025-09-12 18:43:38 +08:00
mikebofs
c40bc46520 fix: asset permission exclude accounts with -action 2025-09-12 11:16:27 +08:00
feng
a732cc614e perf: Asset user login notify 2025-09-11 14:16:00 +08:00
ibuler
bb29d519c6 perf: exclude accounts date expired 2025-09-11 11:42:44 +08:00
ibuler
b56c3a76a7 fix: user option error 2025-09-11 11:21:59 +08:00
fit2bot
ab908d24a7 perf: add i18n (#16001)
* perf: change some api view default limit

* perf: add i18n

---------

Co-authored-by: mikebofs <mikebofs@gmail.com>
2025-09-10 18:18:18 +08:00
fit2bot
79cabe1b3c feat: setting email template content (#15974)
* feat: setting email template content

* perf: tempale list

* perf: custom template render to string

* perf: content serialize valid

* perf: Custom msg template base class

* perf: Template content reset

* perf: Update templates config

* perf: Remove useless code

---------

Co-authored-by: wangruidong <940853815@qq.com>
2025-09-10 16:49:52 +08:00
feng
231b7287c1 perf: Notify info css optimization 2025-09-10 14:04:19 +08:00
feng
be7a4c0d6e perf: Create account unique message 2025-09-09 17:39:18 +08:00
feng
009da19050 perf: Change secret windows password cannot contain > ^ 2025-09-09 16:41:45 +08:00
feng
dfda6b1e08 perf: Change secret del over report 2025-09-09 15:48:03 +08:00
fit2bot
59b40578d8 fix: adhoc SQL Server 2008 (#15984)
* fix: Resolve the issue of errors occurring during automated execution with SQL Server 2008

* fix: adhoc SQL Server 2008

* perf: add todo information

---------

Co-authored-by: halo <wuyihuangw@gmail.com>
2025-09-09 14:26:42 +08:00
Eric
e5db28c014 perf: user add has_public_keys 2025-09-09 14:23:39 +08:00
Eric
6d1f26b0f8 perf: add redis cluster mode setting 2025-09-09 13:51:53 +08:00
Ewall555
2333dbbe33 fix: avoid AttributeError when default_limit is missing 2025-09-09 13:32:52 +08:00
fit2bot
16461b0fa9 perf: support global search (#15961)
* perf: support global search

* perf: change serach

* perf: search model add asset permission

---------

Co-authored-by: mikebofs <mikebofs@gmail.com>
Co-authored-by: ibuler <ibuler@qq.com>
2025-09-05 16:40:18 +08:00
mikebofs
528b0ea1ba perf: change some api view default limit 2025-09-05 16:20:26 +08:00
ibuler
60f06adaa9 fix: wechat or phone decrypt err 2025-09-04 11:59:04 +08:00
Bai
7a6187b95f fix: temp token backend 2025-09-03 18:10:10 +08:00
Bai
aacaf3a174 perf: aks encrypt 2025-09-03 11:16:04 +08:00
Bai
3c9d2534fa perf: aks encrypt 2025-09-03 11:16:04 +08:00
wangruidong
4f79abe678 perf: Connect methods acl allow accept action 2025-09-03 11:00:56 +08:00
fit2bot
ae9956ff91 chore: change readme 2025-09-02 15:22:44 +08:00
Bai
429677e0ce perf: readme 2025-09-02 14:54:28 +08:00
ibuler
034ee65157 perf: decrypt secret logic 2025-09-02 10:38:10 +08:00
Eric
fdd7d9b6b1 perf: add vnc client method 2025-09-02 10:34:39 +08:00
wangruidong
db0e21f5d9 fix: Lazy import Azure and Google Cloud dependencies 2025-08-29 11:10:43 +08:00
wangruidong
468b84eb3d perf: Validate connection token id 2025-08-29 11:09:40 +08:00
ibuler
28d5475d0f perf: try to decrypt then origin value 2025-08-29 11:00:02 +08:00
ibuler
b9c60d856f perf: allow some api page no limits 2025-08-28 17:05:11 +08:00
feng
bd1d73c6dd perf: Report localtime 2025-08-28 15:39:54 +08:00
wangruidong
bf92c756d4 fix: Ensure command arguments are safely quoted in safe_run_cmd 2025-08-28 14:14:55 +08:00
feng
62ebe0d636 perf: Third login redirect url query string 2025-08-27 14:45:56 +08:00
github-actions[bot]
0b1fea8492 perf: Update Dockerfile with new base image tag 2025-08-27 11:05:19 +08:00
mikebofs
65b5f573f8 perf: change requirements 2025-08-27 11:05:19 +08:00
mikebofs
bb639e1fe7 perf: revert django-simple-history version 2025-08-27 10:43:21 +08:00
fit2bot
395b868dcf perf: swagger done (#15865)
* perf: swagger upgrade

* perf: upgrade to drf-spectacular

* perf: 添加部分注解

* perf: swagger done

---------

Co-authored-by: ibuler <ibuler@qq.com>
2025-08-27 10:27:01 +08:00
wangruidong
1350b774b3 perf: Improve chart rendering wait logic in export process 2025-08-26 16:20:22 +08:00
wrd
af7a00c1b1 fix: typo 2025-08-26 15:31:13 +08:00
wangruidong
965ec7007c perf: Enhance eager loading by including labels in queryset 2025-08-26 15:31:13 +08:00
fit2bot
1372fd7535 feat: asset permission support exclude some account
* perf: add perm exclude

* perf: exclude node action account

* perf: add i18n

* perf: pop exclude account

---------

Co-authored-by: mikebofs <mikebofs@gmail.com>
2025-08-26 14:57:57 +08:00
wangruidong
3b0ef4cca7 fix: Add nmap to Dockerfile dependencies 2025-08-25 16:29:10 +08:00
Aaron3S
6832abdaad feat: change some translate 2025-08-25 11:05:49 +08:00
feng
c6bf290dbb perf: Report translate 2025-08-22 18:57:14 +08:00
feng
23ab66c11a perf: Translate 2025-08-22 18:05:30 +08:00
feng
1debaa5547 perf: report perm 2025-08-22 17:53:52 +08:00
Bai
47413966c9 perf: captcha > CAPTCHA 2025-08-22 16:25:45 +08:00
Eric
703f39607c perf: default allow hosts 2025-08-22 14:12:45 +08:00
feng
b65ff0d84c perf: Translate 2025-08-21 18:52:38 +08:00
wangruidong
30d781dd12 fix: Export PDF wait for render done 2025-08-21 18:44:09 +08:00
wangruidong
9551cd4da9 fix: Export PDF with org id 2025-08-21 17:56:26 +08:00
mikebofs
87b456c941 perf: change default width 2025-08-21 16:19:56 +08:00
mikebofs
d4d5224c17 perf: support export dashboard 2025-08-21 16:19:56 +08:00
wangruidong
dabb30d90a perf: Change report name 2025-08-21 16:19:25 +08:00
feng
82192d38e1 perf: Translate 2025-08-21 15:32:04 +08:00
feng
571d2b4575 perf: Custom platform translate 2025-08-21 14:51:38 +08:00
Eric
ea64313c4e perf: fix conenct token platform fields 2025-08-21 14:03:15 +08:00
Bai
8764cdb733 feat: support protocols search 2025-08-21 11:49:18 +08:00
feng
980394efed perf: Transalte 2025-08-21 11:31:29 +08:00
wangruidong
2c94f10d64 fix: The approval setting org admin, and the approver is blank 2025-08-21 10:25:10 +08:00
wangruidong
e1c9f5180d perf: Export pdf using days parameter 2025-08-21 10:23:00 +08:00
wangruidong
3f1d7fa230 perf: Pdf file i18n 2025-08-21 10:23:00 +08:00
wangruidong
44bcd6e399 fix: Send email pdf deps 2025-08-21 10:23:00 +08:00
feng
5f87d98c31 perf: Translate 2025-08-20 18:17:46 +08:00
feng
540becdcbe perf: org admin view settings 2025-08-20 17:11:27 +08:00
feng
6929c4968e perf: Check api 2025-08-20 11:16:46 +08:00
Aaron3S
63b213d3a8 feat: add translate 2025-08-19 19:19:23 +08:00
feng
64fe7a55ec perf: Mongodb ping 2025-08-19 19:08:52 +08:00
feng
27829e09ef perf: Translate 2025-08-19 18:57:23 +08:00
jiangweidong
1bfc7daef6 perf: Avoid Oracle password modification SQL injection risks 2025-08-19 18:55:46 +08:00
Bai
9422aebc5e perf: email i18n 2025-08-19 18:49:25 +08:00
wangruidong
8c0cd20b48 fix: Disable passkey mfa in safe mode 2025-08-19 18:21:33 +08:00
Bai
0c612648a0 perf: email protocol rename 2025-08-19 17:04:32 +08:00
feng
36e01a316c perf: Regular command groups can be filled in with new lines 2025-08-19 15:51:39 +08:00
feng
e1b96e01eb perf: Translate 2025-08-19 15:05:13 +08:00
wangruidong
144f4b4466 fix: Virtual apps manifest i18n 2025-08-19 14:54:03 +08:00
wangruidong
8e007004c2 perf: Translate label for groups parameter 2025-08-19 14:51:52 +08:00
github-actions[bot]
c14f740209 perf: Update Dockerfile with new base image tag 2025-08-19 14:50:45 +08:00
Eric
13a85f062c perf: fix uv pip resolution 2025-08-19 14:50:45 +08:00
fit2bot
7f9d027bd3 perf: Send command translate (#15820)
Co-authored-by: wangruidong <940853815@qq.com>
Co-authored-by: Bryan <jiangjie.bai@fit2cloud.com>
2025-08-18 19:14:48 +08:00
wangruidong
c037ce1c29 perf: Send report email 2025-08-18 19:12:29 +08:00
wangruidong
ee7c6b4708 fix: Init db error 2025-08-18 19:11:59 +08:00
feng
d0e625e322 perf: Translate 2025-08-18 19:08:34 +08:00
feng
c65794a99d perf: KOKO translate 2025-08-18 18:39:42 +08:00
Eric
1e4bca6e24 perf: add lion i18n 2025-08-18 18:28:22 +08:00
feng
c1c5025fbb perf: Account automation report 2025-08-18 17:40:49 +08:00
Eric
96020fa6b4 perf: add lion i18n 2025-08-18 11:42:33 +08:00
wangruidong
5ad6f87a9e fix: Docker build error 2025-08-18 10:53:33 +08:00
feng
9b0c73c9f9 perf: translate 2025-08-15 18:57:46 +08:00
wangruidong
c029714ffd fix: Export pdf failed 2025-08-15 17:42:48 +08:00
wangruidong
c1e8a1b561 fix: Install export pdf deps 2025-08-15 17:42:48 +08:00
feng
21126de2c1 perf: get_cpu_model_count 2025-08-15 16:45:39 +08:00
feng
7d06819bbe perf: foot_js 2025-08-15 16:35:43 +08:00
Eric
92b20fe2ef perf: add lion i18n 2025-08-15 16:24:18 +08:00
feng
4326d35065 perf: User report 2025-08-14 18:55:15 +08:00
feng
4810eae725 perf: group_stats 2025-08-14 16:09:43 +08:00
fit2bot
24f7946b7b perf: change some field to encrypt field (#15842)
* perf: conn token add remote addr

* perf: change some field to encrypt field

---------

Co-authored-by: ibuler <ibuler@qq.com>
2025-08-14 15:05:18 +08:00
王晓阳
4b9c4a550e feat: support vastbase 2025-08-14 14:31:31 +08:00
feng
d3ec23ba85 perf: group_stats 2025-08-14 11:45:36 +08:00
feng
e3c33bca32 perf: User report 2025-08-14 11:12:58 +08:00
feng
0fb7e84678 perf: user asset account report 2025-08-13 18:51:08 +08:00
feng
ab30bfb2d2 perf: mysql pg playbook 2025-08-13 15:15:53 +08:00
feng
d9d034488f fix: report 2025-08-12 19:19:00 +08:00
feng
24bd7b7e1a fix rbac pam 2025-08-12 14:48:16 +08:00
wangruidong
7fb5fd3956 fix: set ansible_timeout for account connectivity tasks 2025-08-11 10:37:23 +08:00
feng
9c621f5ff5 perf: rbac pam 2025-08-08 13:52:38 +08:00
feng
ac8998b9ee perf: Account risk delete normal account 2025-08-06 17:02:53 +08:00
wangruidong
b258537890 fix: Fallback to browser language if user language is not set 2025-08-06 14:15:30 +08:00
fit2bot
b38d83c578 feat: report charts (#15630)
* perf: initial

* perf: basic finished

* perf: depend

* perf: Update Dockerfile with new base image tag

* perf: Add user report api

* perf: Update Dockerfile with new base image tag

* perf: Use user report api

* perf: Update Dockerfile with new base image tag

* perf: user login report

* perf: Update Dockerfile with new base image tag

* perf: user change password

* perf: change password dashboard

* perf: Update Dockerfile with new base image tag

* perf: Translate

* perf: asset api

* perf: asset activity

* perf: Asset report

* perf: add charts_map

* perf: account report

* perf: Translate

* perf: account automation

* perf: Account automation

* perf: title

* perf: Update Dockerfile with new base image tag

---------

Co-authored-by: ibuler <ibuler@qq.com>
Co-authored-by: feng <1304903146@qq.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: wangruidong <940853815@qq.com>
Co-authored-by: feng626 <57284900+feng626@users.noreply.github.com>
2025-08-06 14:05:38 +08:00
feng
257f290d18 perf: Translate 2025-08-06 11:33:52 +08:00
wangruidong
d185be2180 perf: Optimize redis connection number 2025-08-04 18:53:34 +08:00
ibuler
4e33b5b478 perf: some risk example file path 2025-08-01 10:35:15 +08:00
wangruidong
1406437d4e fix: Failed to switch languages 2025-08-01 10:24:17 +08:00
feng
e46aa95980 perf: check_asset_permission_will_expired filter is_active=True 2025-08-01 10:18:52 +08:00
Eric
c619a35a04 perf: update lion i18n tip 2025-08-01 10:18:12 +08:00
wangruidong
29f10bf10e perf: ES connect error detail 2025-07-31 17:15:55 +08:00
wangruidong
a822905ae7 fix: When the cas user doesn't exist, you will be prompted with an error when logging in. 2025-07-31 17:15:18 +08:00
zhaojisen
dc5a743f4f revert style 2025-07-30 14:27:52 +08:00
zhaojisen
1de8781704 Fixed: Fix the issue with the login page footer 2025-07-30 14:27:52 +08:00
wangruidong
f3d9f4c446 fix: Failed to switch languages 2025-07-29 16:40:30 +08:00
jiangweidong
6b5d5c15ae feat: Add an embedded form to ChatAI 2025-07-29 14:15:01 +08:00
feng
1074a0df19 perf: MFA coce reuse 2025-07-29 11:00:39 +08:00
Eric
04dca794dd fix: fix chrome_app password_manager dialog 2025-07-29 10:21:46 +08:00
ibuler
14e0396508 perf: change ip db path 2025-07-29 10:20:37 +08:00
wangruidong
835eb2e3d0 perf: Improve error handling for email sending in tasks 2025-07-28 10:30:42 +08:00
ibuler
be24f28d9b perf: in safe mode passkey cannot be as mfa 2025-07-25 10:50:46 +08:00
wangruidong
26cea550c4 fix: The applet list is not translated. 2025-07-25 10:49:47 +08:00
wangruidong
36ae076cb0 fix: Open redirect security vulnerability 2025-07-24 15:50:05 +08:00
feng
51c5294fb4 perf: Ticket filter org 2025-07-24 14:36:15 +08:00
feng
da083fffa3 perf: Translate email help text 2025-07-24 14:35:21 +08:00
feng
1df04d2a94 perf: Pam rbac 2025-07-23 10:21:38 +08:00
Eric
299e52cd11 perf: vnc_guide method only by xpack 2025-07-22 14:37:38 +08:00
feng
38b268b104 fix: Circular import 2025-07-22 14:36:22 +08:00
wangruidong
6095e9c9bd perf: Modify the layout to flex 2025-07-22 14:35:05 +08:00
ibuler
c4a348aac6 perf: remove client redirect api 2025-07-22 14:34:11 +08:00
feng
75575af56f perf: Callback client 2025-07-22 13:51:08 +08:00
430 changed files with 47747 additions and 13062 deletions

26
.github/.github/issue-spam-config.json vendored Normal file
View File

@@ -0,0 +1,26 @@
{
"dry_run": false,
"min_account_age_days": 3,
"max_urls_for_spam": 1,
"min_body_len_for_links": 40,
"spam_words": [
"call now",
"zadzwoń",
"zadzwoń teraz",
"kontakt",
"telefon",
"telefone",
"contato",
"suporte",
"infolinii",
"click here",
"buy now",
"subscribe",
"visit"
],
"bracket_max": 6,
"special_char_density_threshold": 0.12,
"phone_regex": "\\+?\\d[\\d\\-\\s\\(\\)\\.]{6,}\\d",
"labels_for_spam": ["spam"],
"labels_for_review": ["needs-triage"]
}

View File

@@ -1,74 +1,72 @@
name: Build and Push Base Image
on:
pull_request:
branches:
- 'dev'
- 'v*'
paths:
- poetry.lock
- pyproject.toml
- Dockerfile-base
- package.json
- go.mod
- yarn.lock
- pom.xml
- install_deps.sh
- utils/clean_site_packages.sh
types:
- opened
- synchronize
- reopened
pull_request:
branches:
- 'dev'
- 'v*'
paths:
- poetry.lock
- pyproject.toml
- Dockerfile-base
- package.json
- go.mod
- yarn.lock
- pom.xml
- install_deps.sh
- utils/clean_site_packages.sh
types:
- opened
- synchronize
- reopened
jobs:
build-and-push:
runs-on: ubuntu-22.04
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.ref }}
build-and-push:
runs-on: ubuntu-22.04
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.ref }}
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
with:
image: tonistiigi/binfmt:qemu-v7.0.0-28
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to DockerHub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Login to DockerHub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Extract date
id: vars
run: echo "IMAGE_TAG=$(date +'%Y%m%d_%H%M%S')" >> $GITHUB_ENV
- name: Extract date
id: vars
run: echo "IMAGE_TAG=$(date +'%Y%m%d_%H%M%S')" >> $GITHUB_ENV
- name: Extract repository name
id: repo
run: echo "REPO=$(basename ${{ github.repository }})" >> $GITHUB_ENV
- name: Extract repository name
id: repo
run: echo "REPO=$(basename ${{ github.repository }})" >> $GITHUB_ENV
- name: Build and push multi-arch image
uses: docker/build-push-action@v6
with:
platforms: linux/amd64,linux/arm64
push: true
file: Dockerfile-base
tags: jumpserver/core-base:${{ env.IMAGE_TAG }}
- name: Build and push multi-arch image
uses: docker/build-push-action@v6
with:
platforms: linux/amd64,linux/arm64
push: true
file: Dockerfile-base
tags: jumpserver/core-base:${{ env.IMAGE_TAG }}
- name: Update Dockerfile
run: |
sed -i 's|-base:.* AS stage-build|-base:${{ env.IMAGE_TAG }} AS stage-build|' Dockerfile
- name: Update Dockerfile
run: |
sed -i 's|-base:.* AS stage-build|-base:${{ env.IMAGE_TAG }} AS stage-build|' Dockerfile
- name: Commit changes
run: |
git config --global user.name 'github-actions[bot]'
git config --global user.email 'github-actions[bot]@users.noreply.github.com'
git add Dockerfile
git commit -m "perf: Update Dockerfile with new base image tag"
git push origin ${{ github.event.pull_request.head.ref }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Commit changes
run: |
git config --global user.name 'github-actions[bot]'
git config --global user.email 'github-actions[bot]@users.noreply.github.com'
git add Dockerfile
git commit -m "perf: Update Dockerfile with new base image tag"
git push origin ${{ github.event.pull_request.head.ref }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -0,0 +1,46 @@
name: Build and Push Python Base Image
on:
workflow_dispatch:
inputs:
tag:
description: 'Tag to build'
required: true
default: '3.11-slim-bullseye-v1'
type: string
jobs:
build-and-push:
runs-on: ubuntu-22.04
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.ref }}
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
with:
image: tonistiigi/binfmt:qemu-v7.0.0-28
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to DockerHub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Extract repository name
id: repo
run: echo "REPO=$(basename ${{ github.repository }})" >> $GITHUB_ENV
- name: Build and push multi-arch image
uses: docker/build-push-action@v6
with:
platforms: linux/amd64,linux/arm64
push: true
file: Dockerfile-python
tags: jumpserver/core-base:python-${{ inputs.tag }}

123
.github/workflows/cleanup-branches.yml vendored Normal file
View File

@@ -0,0 +1,123 @@
name: Cleanup PR Branches
on:
schedule:
# 每天凌晨2点运行
- cron: '0 2 * * *'
workflow_dispatch:
# 允许手动触发
inputs:
dry_run:
description: 'Dry run mode (default: true)'
required: false
default: 'true'
type: boolean
jobs:
cleanup-branches:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0 # 获取所有分支和提交历史
- name: Setup Git
run: |
git config --global user.name "GitHub Actions"
git config --global user.email "actions@github.com"
- name: Get dry run setting
id: dry-run
run: |
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
echo "dry_run=${{ github.event.inputs.dry_run }}" >> $GITHUB_OUTPUT
else
echo "dry_run=false" >> $GITHUB_OUTPUT
fi
- name: Cleanup branches
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
DRY_RUN: ${{ steps.dry-run.outputs.dry_run }}
run: |
echo "Starting branch cleanup..."
echo "Dry run mode: $DRY_RUN"
# 获取所有本地分支
git fetch --all --prune
# 获取以 pr 或 repr 开头的分支
branches=$(git branch -r | grep -E 'origin/(pr|repr)' | sed 's/origin\///' | grep -v 'HEAD')
echo "Found branches matching pattern:"
echo "$branches"
deleted_count=0
skipped_count=0
for branch in $branches; do
echo ""
echo "Processing branch: $branch"
# 检查分支是否有未合并的PR
pr_info=$(gh pr list --head "$branch" --state open --json number,title,state 2>/dev/null)
if [ $? -eq 0 ] && [ "$pr_info" != "[]" ]; then
echo " ⚠️ Branch has open PR(s), skipping deletion"
echo " PR info: $pr_info"
skipped_count=$((skipped_count + 1))
continue
fi
# 检查分支是否有已合并的PR可选如果PR已合并也可以删除
merged_pr_info=$(gh pr list --head "$branch" --state merged --json number,title,state 2>/dev/null)
if [ $? -eq 0 ] && [ "$merged_pr_info" != "[]" ]; then
echo " ✅ Branch has merged PR(s), safe to delete"
echo " Merged PR info: $merged_pr_info"
else
echo " No PRs found for this branch"
fi
# 执行删除操作
if [ "$DRY_RUN" = "true" ]; then
echo " 🔍 [DRY RUN] Would delete branch: $branch"
deleted_count=$((deleted_count + 1))
else
echo " 🗑️ Deleting branch: $branch"
# 删除远程分支
if git push origin --delete "$branch" 2>/dev/null; then
echo " ✅ Successfully deleted remote branch: $branch"
deleted_count=$((deleted_count + 1))
else
echo " ❌ Failed to delete remote branch: $branch"
fi
fi
done
echo ""
echo "=== Cleanup Summary ==="
echo "Branches processed: $(echo "$branches" | wc -l)"
echo "Branches deleted: $deleted_count"
echo "Branches skipped: $skipped_count"
if [ "$DRY_RUN" = "true" ]; then
echo ""
echo "🔍 This was a DRY RUN - no branches were actually deleted"
echo "To perform actual deletion, run this workflow manually with dry_run=false"
fi
- name: Create summary
if: always()
run: |
echo "## Branch Cleanup Summary" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Workflow:** ${{ github.workflow }}" >> $GITHUB_STEP_SUMMARY
echo "**Run ID:** ${{ github.run_id }}" >> $GITHUB_STEP_SUMMARY
echo "**Dry Run:** ${{ steps.dry-run.outputs.dry_run }}" >> $GITHUB_STEP_SUMMARY
echo "**Triggered by:** ${{ github.event_name }}" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "Check the logs above for detailed information about processed branches." >> $GITHUB_STEP_SUMMARY

View File

@@ -1,10 +1,33 @@
on: [push, pull_request, release]
on:
push:
pull_request:
types: [opened, synchronize, closed]
release:
types: [created]
name: JumpServer repos generic handler
jobs:
generic_handler:
name: Run generic handler
handle_pull_request:
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
steps:
- uses: jumpserver/action-generic-handler@master
env:
GITHUB_TOKEN: ${{ secrets.PRIVATE_TOKEN }}
I18N_TOKEN: ${{ secrets.I18N_TOKEN }}
handle_push:
if: github.event_name == 'push'
runs-on: ubuntu-latest
steps:
- uses: jumpserver/action-generic-handler@master
env:
GITHUB_TOKEN: ${{ secrets.PRIVATE_TOKEN }}
I18N_TOKEN: ${{ secrets.I18N_TOKEN }}
handle_release:
if: github.event_name == 'release'
runs-on: ubuntu-latest
steps:
- uses: jumpserver/action-generic-handler@master

View File

@@ -1,11 +1,9 @@
name: 🔀 Sync mirror to Gitee
on:
push:
branches:
- master
- dev
create:
schedule:
# 每天凌晨3点运行
- cron: '0 3 * * *'
jobs:
mirror:
@@ -14,7 +12,6 @@ jobs:
steps:
- name: mirror
continue-on-error: true
if: github.event_name == 'push' || (github.event_name == 'create' && github.event.ref_type == 'tag')
uses: wearerequired/git-mirror-action@v1
env:
SSH_PRIVATE_KEY: ${{ secrets.GITEE_SSH_PRIVATE_KEY }}

View File

@@ -1,4 +1,4 @@
FROM jumpserver/core-base:20250509_094529 AS stage-build
FROM jumpserver/core-base:20251128_025056 AS stage-build
ARG VERSION
@@ -19,7 +19,7 @@ RUN set -ex \
&& python manage.py compilemessages
FROM python:3.11-slim-bullseye
FROM python:3.11-slim-trixie
ENV LANG=en_US.UTF-8 \
PATH=/opt/py3/bin:$PATH
@@ -33,12 +33,13 @@ ARG TOOLS=" \
default-libmysqlclient-dev \
openssh-client \
sshpass \
nmap \
bubblewrap"
ARG APT_MIRROR=http://deb.debian.org
RUN set -ex \
&& sed -i "s@http://.*.debian.org@${APT_MIRROR}@g" /etc/apt/sources.list \
&& sed -i "s@http://.*.debian.org@${APT_MIRROR}@g" /etc/apt/sources.list.d/debian.sources \
&& ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
&& apt-get update > /dev/null \
&& apt-get -y install --no-install-recommends ${DEPENDENCIES} \

View File

@@ -1,6 +1,5 @@
FROM python:3.11-slim-bullseye
FROM python:3.11.14-slim-trixie
ARG TARGETARCH
COPY --from=ghcr.io/astral-sh/uv:0.6.14 /uv /uvx /usr/local/bin/
# Install APT dependencies
ARG DEPENDENCIES=" \
ca-certificates \
@@ -22,13 +21,13 @@ RUN --mount=type=cache,target=/var/cache/apt,sharing=locked,id=core \
set -ex \
&& rm -f /etc/apt/apt.conf.d/docker-clean \
&& echo 'Binary::apt::APT::Keep-Downloaded-Packages "true";' > /etc/apt/apt.conf.d/keep-cache \
&& sed -i "s@http://.*.debian.org@${APT_MIRROR}@g" /etc/apt/sources.list \
&& sed -i "s@http://.*.debian.org@${APT_MIRROR}@g" /etc/apt/sources.list.d/debian.sources \
&& apt-get update > /dev/null \
&& apt-get -y install --no-install-recommends ${DEPENDENCIES} \
&& echo "no" | dpkg-reconfigure dash
# Install bin tools
ARG CHECK_VERSION=v1.0.4
ARG CHECK_VERSION=v1.0.5
RUN set -ex \
&& wget https://github.com/jumpserver-dev/healthcheck/releases/download/${CHECK_VERSION}/check-${CHECK_VERSION}-linux-${TARGETARCH}.tar.gz \
&& tar -xf check-${CHECK_VERSION}-linux-${TARGETARCH}.tar.gz \
@@ -41,12 +40,10 @@ RUN set -ex \
WORKDIR /opt/jumpserver
ARG PIP_MIRROR=https://pypi.org/simple
ENV POETRY_PYPI_MIRROR_URL=${PIP_MIRROR}
ENV ANSIBLE_COLLECTIONS_PATHS=/opt/py3/lib/python3.11/site-packages/ansible_collections
ENV LANG=en_US.UTF-8 \
PATH=/opt/py3/bin:$PATH
ENV UV_LINK_MODE=copy
ENV SETUPTOOLS_SCM_PRETEND_VERSION=3.4.5
RUN --mount=type=cache,target=/root/.cache \
--mount=type=bind,source=pyproject.toml,target=pyproject.toml \
@@ -54,6 +51,7 @@ RUN --mount=type=cache,target=/root/.cache \
--mount=type=bind,source=requirements/collections.yml,target=collections.yml \
--mount=type=bind,source=requirements/static_files.sh,target=utils/static_files.sh \
set -ex \
&& pip install uv -i${PIP_MIRROR} \
&& uv venv \
&& uv pip install -i${PIP_MIRROR} -r pyproject.toml \
&& ln -sf $(pwd)/.venv /opt/py3 \

View File

@@ -13,8 +13,9 @@ ARG TOOLS=" \
nmap \
telnet \
vim \
postgresql-client-13 \
wget"
postgresql-client \
wget \
poppler-utils"
RUN set -ex \
&& apt-get update \
@@ -27,5 +28,5 @@ WORKDIR /opt/jumpserver
ARG PIP_MIRROR=https://pypi.org/simple
RUN set -ex \
&& uv pip install -i${PIP_MIRROR} --group xpack
&& uv pip install -i${PIP_MIRROR} --group xpack \
&& playwright install chromium --with-deps --only-shell

View File

@@ -2,7 +2,7 @@
<a name="readme-top"></a>
<a href="https://jumpserver.com" target="_blank"><img src="https://download.jumpserver.org/images/jumpserver-logo.svg" alt="JumpServer" width="300" /></a>
## An open-source PAM tool (Bastion Host)
## An open-source PAM platform (Bastion Host)
[![][license-shield]][license-link]
[![][docs-shield]][docs-link]
@@ -19,7 +19,7 @@
## What is JumpServer?
JumpServer is an open-source Privileged Access Management (PAM) tool that provides DevOps and IT teams with on-demand and secure access to SSH, RDP, Kubernetes, Database and RemoteApp endpoints through a web browser.
JumpServer is an open-source Privileged Access Management (PAM) platform that provides DevOps and IT teams with on-demand and secure access to SSH, RDP, Kubernetes, Database and RemoteApp endpoints through a web browser.
<picture>
@@ -77,7 +77,8 @@ JumpServer consists of multiple key components, which collectively form the func
| [Luna](https://github.com/jumpserver/luna) | <a href="https://github.com/jumpserver/luna/releases"><img alt="Luna release" src="https://img.shields.io/github/release/jumpserver/luna.svg" /></a> | JumpServer Web Terminal |
| [KoKo](https://github.com/jumpserver/koko) | <a href="https://github.com/jumpserver/koko/releases"><img alt="Koko release" src="https://img.shields.io/github/release/jumpserver/koko.svg" /></a> | JumpServer Character Protocol Connector |
| [Lion](https://github.com/jumpserver/lion) | <a href="https://github.com/jumpserver/lion/releases"><img alt="Lion release" src="https://img.shields.io/github/release/jumpserver/lion.svg" /></a> | JumpServer Graphical Protocol Connector |
| [Chen](https://github.com/jumpserver/chen) | <a href="https://github.com/jumpserver/chen/releases"><img alt="Chen release" src="https://img.shields.io/github/release/jumpserver/chen.svg" /> | JumpServer Web DB |
| [Chen](https://github.com/jumpserver/chen) | <a href="https://github.com/jumpserver/chen/releases"><img alt="Chen release" src="https://img.shields.io/github/release/jumpserver/chen.svg" /> | JumpServer Web DB
| [Client](https://github.com/jumpserver/clients) | <a href="https://github.com/jumpserver/clients/releases"><img alt="Clients release" src="https://img.shields.io/github/release/jumpserver/clients.svg" /> | JumpServer Client |
| [Tinker](https://github.com/jumpserver/tinker) | <img alt="Tinker" src="https://img.shields.io/badge/release-private-red" /> | JumpServer Remote Application Connector (Windows) |
| [Panda](https://github.com/jumpserver/Panda) | <img alt="Panda" src="https://img.shields.io/badge/release-private-red" /> | JumpServer EE Remote Application Connector (Linux) |
| [Razor](https://github.com/jumpserver/razor) | <img alt="Chen" src="https://img.shields.io/badge/release-private-red" /> | JumpServer EE RDP Proxy Connector |

View File

@@ -1,16 +1,18 @@
from django.db import transaction
from django.shortcuts import get_object_or_404
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers as drf_serializers
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView, CreateAPIView
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST
from accounts import serializers
from accounts.const import ChangeSecretRecordStatusChoice
from accounts.filters import AccountFilterSet, NodeFilterBackend
from accounts.mixins import AccountRecordViewLogMixin
from accounts.models import Account, ChangeSecretRecord
from assets.const.gpt import create_or_update_chatx_resources
from assets.models import Asset, Node
from authentication.permissions import UserConfirmation, ConfirmType
from common.api.mixin import ExtraFilterFieldsMixin
@@ -18,6 +20,7 @@ from common.drf.filters import AttrRulesFilterBackend
from common.permissions import IsValidUser
from common.utils import lazyproperty, get_logger
from orgs.mixins.api import OrgBulkModelViewSet
from orgs.utils import tmp_to_root_org
from rbac.permissions import RBACPermission
logger = get_logger(__file__)
@@ -41,8 +44,9 @@ class AccountViewSet(OrgBulkModelViewSet):
'partial_update': ['accounts.change_account'],
'su_from_accounts': 'accounts.view_account',
'clear_secret': 'accounts.change_account',
'move_to_assets': 'accounts.create_account',
'copy_to_assets': 'accounts.create_account',
'move_to_assets': 'accounts.delete_account',
'copy_to_assets': 'accounts.add_account',
'chat': 'accounts.view_account',
}
export_as_zip = True
@@ -152,6 +156,13 @@ class AccountViewSet(OrgBulkModelViewSet):
def copy_to_assets(self, request, *args, **kwargs):
return self._copy_or_move_to_assets(request, move=False)
@action(methods=['get'], detail=False, url_path='chat')
def chat(self, request, *args, **kwargs):
with tmp_to_root_org():
__, account = create_or_update_chatx_resources()
serializer = self.get_serializer(account)
return Response(serializer.data)
class AccountSecretsViewSet(AccountRecordViewLogMixin, AccountViewSet):
"""
@@ -174,12 +185,66 @@ class AssetAccountBulkCreateApi(CreateAPIView):
'POST': 'accounts.add_account',
}
@staticmethod
def get_all_assets(base_payload: dict):
nodes = base_payload.pop('nodes', [])
asset_ids = base_payload.pop('assets', [])
nodes = Node.objects.filter(id__in=nodes).only('id', 'key')
node_asset_ids = Node.get_nodes_all_assets(*nodes).values_list('id', flat=True)
asset_ids = set(asset_ids + list(node_asset_ids))
return Asset.objects.filter(id__in=asset_ids)
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
data = serializer.create(serializer.validated_data)
serializer = serializers.AssetAccountBulkSerializerResultSerializer(data, many=True)
return Response(data=serializer.data, status=HTTP_200_OK)
if hasattr(request.data, "copy"):
base_payload = request.data.copy()
else:
base_payload = dict(request.data)
templates = base_payload.pop("template", None)
assets = self.get_all_assets(base_payload)
if not assets.exists():
error = _("No valid assets found for account creation.")
return Response(
data={
"detail": error,
"code": "no_valid_assets"
},
status=HTTP_400_BAD_REQUEST
)
result = []
errors = []
def handle_one(_payload):
try:
ser = self.get_serializer(data=_payload)
ser.is_valid(raise_exception=True)
data = ser.bulk_create(ser.validated_data, assets)
if isinstance(data, (list, tuple)):
result.extend(data)
else:
result.append(data)
except drf_serializers.ValidationError as e:
errors.extend(list(e.detail))
except Exception as e:
errors.extend([str(e)])
if not templates:
handle_one(base_payload)
else:
if not isinstance(templates, (list, tuple)):
templates = [templates]
for tpl in templates:
payload = dict(base_payload)
payload["template"] = tpl
handle_one(payload)
if errors:
raise drf_serializers.ValidationError(errors)
out_ser = serializers.AssetAccountBulkSerializerResultSerializer(result, many=True)
return Response(data=out_ser.data, status=HTTP_200_OK)
class AccountHistoriesSecretAPI(ExtraFilterFieldsMixin, AccountRecordViewLogMixin, ListAPIView):
@@ -190,6 +255,7 @@ class AccountHistoriesSecretAPI(ExtraFilterFieldsMixin, AccountRecordViewLogMixi
rbac_perms = {
'GET': 'accounts.view_accountsecret',
}
queryset = Account.history.model.objects.none()
@lazyproperty
def account(self) -> Account:

View File

@@ -25,7 +25,8 @@ class IntegrationApplicationViewSet(OrgBulkModelViewSet):
}
rbac_perms = {
'get_once_secret': 'accounts.change_integrationapplication',
'get_account_secret': 'accounts.view_integrationapplication'
'get_account_secret': 'accounts.view_integrationapplication',
'get_sdks_info': 'accounts.view_integrationapplication'
}
def read_file(self, path):
@@ -36,7 +37,6 @@ class IntegrationApplicationViewSet(OrgBulkModelViewSet):
@action(
['GET'], detail=False, url_path='sdks',
permission_classes=[IsValidUser]
)
def get_sdks_info(self, request, *args, **kwargs):
code_suffix_mapper = {

View File

@@ -20,7 +20,7 @@ __all__ = ['PamDashboardApi']
class PamDashboardApi(APIView):
http_method_names = ['get']
rbac_perms = {
'GET': 'accounts.view_account',
'GET': 'rbac.view_pam',
}
@staticmethod

View File

@@ -12,6 +12,8 @@ class VirtualAccountViewSet(OrgBulkModelViewSet):
filterset_fields = ('alias',)
def get_queryset(self):
if getattr(self, "swagger_fake_view", False):
return VirtualAccount.objects.none()
return VirtualAccount.get_or_init_queryset()
def get_object(self, ):

View File

@@ -41,6 +41,7 @@ class AutomationAssetsListApi(generics.ListAPIView):
class AutomationRemoveAssetApi(generics.UpdateAPIView):
model = BaseAutomation
queryset = BaseAutomation.objects.all()
serializer_class = serializers.UpdateAssetSerializer
http_method_names = ['patch']
@@ -59,6 +60,7 @@ class AutomationRemoveAssetApi(generics.UpdateAPIView):
class AutomationAddAssetApi(generics.UpdateAPIView):
model = BaseAutomation
queryset = BaseAutomation.objects.all()
serializer_class = serializers.UpdateAssetSerializer
http_method_names = ['patch']

View File

@@ -154,12 +154,10 @@ class ChangSecretAddAssetApi(AutomationAddAssetApi):
model = ChangeSecretAutomation
serializer_class = serializers.ChangeSecretUpdateAssetSerializer
class ChangSecretNodeAddRemoveApi(AutomationNodeAddRemoveApi):
model = ChangeSecretAutomation
serializer_class = serializers.ChangeSecretUpdateNodeSerializer
class ChangeSecretStatusViewSet(OrgBulkModelViewSet):
perm_model = ChangeSecretAutomation
filterset_class = ChangeSecretStatusFilterSet

View File

@@ -62,7 +62,8 @@ class ChangeSecretDashboardApi(APIView):
status_counts = defaultdict(lambda: defaultdict(int))
for date_finished, status in results:
date_str = str(date_finished.date())
dt_local = timezone.localtime(date_finished)
date_str = str(dt_local.date())
if status == ChangeSecretRecordStatusChoice.failed:
status_counts[date_str]['failed'] += 1
elif status == ChangeSecretRecordStatusChoice.success:
@@ -90,10 +91,10 @@ class ChangeSecretDashboardApi(APIView):
def get_change_secret_asset_queryset(self):
qs = self.change_secrets_queryset
node_ids = qs.filter(nodes__isnull=False).values_list('nodes', flat=True).distinct()
nodes = Node.objects.filter(id__in=node_ids)
node_ids = qs.values_list('nodes', flat=True).distinct()
nodes = Node.objects.filter(id__in=node_ids).only('id', 'key')
node_asset_ids = Node.get_nodes_all_assets(*nodes).values_list('id', flat=True)
direct_asset_ids = qs.filter(assets__isnull=False).values_list('assets', flat=True).distinct()
direct_asset_ids = qs.values_list('assets', flat=True).distinct()
asset_ids = set(list(direct_asset_ids) + list(node_asset_ids))
return Asset.objects.filter(id__in=asset_ids)

View File

@@ -45,10 +45,10 @@ class CheckAccountAutomationViewSet(OrgBulkModelViewSet):
class CheckAccountExecutionViewSet(AutomationExecutionViewSet):
rbac_perms = (
("list", "accounts.view_checkaccountexecution"),
("retrieve", "accounts.view_checkaccountsexecution"),
("retrieve", "accounts.view_checkaccountexecution"),
("create", "accounts.add_checkaccountexecution"),
("adhoc", "accounts.add_checkaccountexecution"),
("report", "accounts.view_checkaccountsexecution"),
("report", "accounts.view_checkaccountexecution"),
)
ordering = ("-date_created",)
tp = AutomationTypes.check_account
@@ -150,6 +150,9 @@ class CheckAccountEngineViewSet(JMSModelViewSet):
http_method_names = ['get', 'options']
def get_queryset(self):
if getattr(self, "swagger_fake_view", False):
return CheckAccountEngine.objects.none()
return CheckAccountEngine.get_default_engines()
def filter_queryset(self, queryset: list):

View File

@@ -63,12 +63,10 @@ class PushAccountRemoveAssetApi(AutomationRemoveAssetApi):
model = PushAccountAutomation
serializer_class = serializers.PushAccountUpdateAssetSerializer
class PushAccountAddAssetApi(AutomationAddAssetApi):
model = PushAccountAutomation
serializer_class = serializers.PushAccountUpdateAssetSerializer
class PushAccountNodeAddRemoveApi(AutomationNodeAddRemoveApi):
model = PushAccountAutomation
serializer_class = serializers.PushAccountUpdateNodeSerializer
serializer_class = serializers.PushAccountUpdateNodeSerializer

View File

@@ -235,8 +235,8 @@ class AccountBackupHandler:
except Exception as e:
error = str(e)
print(f'\033[31m>>> {error}\033[0m')
self.execution.status = Status.error
self.execution.summary['error'] = error
self.manager.status = Status.error
self.manager.summary['error'] = error
def backup_by_obj_storage(self):
object_id = self.execution.snapshot.get('id')

View File

@@ -113,6 +113,16 @@ class BaseChangeSecretPushManager(AccountBasePlaybookManager):
if host.get('error'):
return host
inventory_hosts = []
if asset.type == HostTypes.WINDOWS:
if self.secret_type == SecretType.SSH_KEY:
host['error'] = _("Windows does not support SSH key authentication")
return host
new_secret = self.get_secret(account)
if '>' in new_secret or '^' in new_secret:
host['error'] = _("Windows password cannot contain special characters like > ^")
return host
host['ssh_params'] = {}
accounts = self.get_accounts(account)
@@ -130,11 +140,6 @@ class BaseChangeSecretPushManager(AccountBasePlaybookManager):
if asset.type == HostTypes.WINDOWS:
accounts = accounts.filter(secret_type=SecretType.PASSWORD)
inventory_hosts = []
if asset.type == HostTypes.WINDOWS and self.secret_type == SecretType.SSH_KEY:
print(f'Windows {asset} does not support ssh key push')
return inventory_hosts
for account in accounts:
h = deepcopy(host)
h['name'] += '(' + account.username + ')' # To distinguish different accounts

View File

@@ -53,4 +53,6 @@
ssl_certfile: "{{ jms_asset.secret_info.client_key | default('') }}"
connection_options:
- tlsAllowInvalidHostnames: "{{ jms_asset.spec_info.allow_invalid_cert}}"
when: check_conn_after_change
when: check_conn_after_change
register: result
failed_when: not result.is_available

View File

@@ -39,7 +39,8 @@
name: "{{ account.username }}"
password: "{{ account.secret }}"
host: "%"
priv: "{{ account.username + '.*:USAGE' if db_name == '' else db_name + '.*:ALL' }}"
priv: "{{ omit if db_name == '' else db_name + '.*:ALL' }}"
append_privs: "{{ db_name != '' | bool }}"
ignore_errors: true
when: db_info is succeeded

View File

@@ -56,3 +56,5 @@
ssl_key: "{{ ssl_key if check_ssl and ssl_key | length > 0 else omit }}"
ssl_mode: "{{ jms_asset.spec_info.pg_ssl_mode }}"
when: check_conn_after_change
register: result
failed_when: not result.is_available

View File

@@ -5,12 +5,14 @@
tasks:
- name: Test SQLServer connection
community.general.mssql_script:
mssql_script:
login_user: "{{ jms_account.username }}"
login_password: "{{ jms_account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
name: '{{ jms_asset.spec_info.db_name }}'
encryption: "{{ jms_asset.encryption | default(None) }}"
tds_version: "{{ jms_asset.tds_version | default(None) }}"
script: |
SELECT @@version
register: db_info
@@ -23,45 +25,53 @@
var: info
- name: Check whether SQLServer User exist
community.general.mssql_script:
mssql_script:
login_user: "{{ jms_account.username }}"
login_password: "{{ jms_account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
name: '{{ jms_asset.spec_info.db_name }}'
encryption: "{{ jms_asset.encryption | default(None) }}"
tds_version: "{{ jms_asset.tds_version | default(None) }}"
script: "SELECT 1 from sys.sql_logins WHERE name='{{ account.username }}';"
when: db_info is succeeded
register: user_exist
- name: Change SQLServer password
community.general.mssql_script:
mssql_script:
login_user: "{{ jms_account.username }}"
login_password: "{{ jms_account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
name: '{{ jms_asset.spec_info.db_name }}'
encryption: "{{ jms_asset.encryption | default(None) }}"
tds_version: "{{ jms_asset.tds_version | default(None) }}"
script: "ALTER LOGIN {{ account.username }} WITH PASSWORD = '{{ account.secret }}', DEFAULT_DATABASE = {{ jms_asset.spec_info.db_name }}; select @@version"
ignore_errors: true
when: user_exist.query_results[0] | length != 0
- name: Add SQLServer user
community.general.mssql_script:
mssql_script:
login_user: "{{ jms_account.username }}"
login_password: "{{ jms_account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
name: '{{ jms_asset.spec_info.db_name }}'
encryption: "{{ jms_asset.encryption | default(None) }}"
tds_version: "{{ jms_asset.tds_version | default(None) }}"
script: "CREATE LOGIN {{ account.username }} WITH PASSWORD = '{{ account.secret }}', DEFAULT_DATABASE = {{ jms_asset.spec_info.db_name }}; CREATE USER {{ account.username }} FOR LOGIN {{ account.username }}; select @@version"
ignore_errors: true
when: user_exist.query_results[0] | length == 0
- name: Verify password
community.general.mssql_script:
mssql_script:
login_user: "{{ account.username }}"
login_password: "{{ account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
name: '{{ jms_asset.spec_info.db_name }}'
encryption: "{{ jms_asset.encryption | default(None) }}"
tds_version: "{{ jms_asset.tds_version | default(None) }}"
script: |
SELECT @@version
when: check_conn_after_change

View File

@@ -18,6 +18,7 @@
uid: "{{ params.uid | int if params.uid | length > 0 else omit }}"
shell: "{{ params.shell if params.shell | length > 0 else omit }}"
home: "{{ params.home if params.home | length > 0 else '/home/' + account.username }}"
group: "{{ params.group if params.group | length > 0 else omit }}"
groups: "{{ params.groups if params.groups | length > 0 else omit }}"
append: "{{ true if params.groups | length > 0 else false }}"
expires: -1

View File

@@ -28,6 +28,12 @@ params:
default: ''
help_text: "{{ 'Params home help text' | trans }}"
- name: group
type: str
label: "{{ 'Params group label' | trans }}"
default: ''
help_text: "{{ 'Params group help text' | trans }}"
- name: groups
type: str
label: "{{ 'Params groups label' | trans }}"
@@ -61,6 +67,11 @@ i18n:
ja: 'デフォルトのホームディレクトリ /home/{アカウントユーザ名}'
en: 'Default home directory /home/{account username}'
Params group help text:
zh: '请输入用户组(名字或数字),只能输入一个(需填写已存在的用户组)'
ja: 'ユーザー グループ (名前または番号) を入力してください。入力できるのは 1 つだけです (既存のユーザー グループを入力する必要があります)'
en: 'Please enter a user group (name or number), only one can be entered (must fill in an existing user group)'
Params groups help text:
zh: '请输入用户组,多个用户组使用逗号分隔(需填写已存在的用户组)'
ja: 'グループを入力してください。複数のグループはコンマで区切ってください(既存のグループを入力してください)'
@@ -86,6 +97,11 @@ i18n:
ja: 'グループ'
en: 'Groups'
Params group label:
zh: '主组'
ja: '主组'
en: 'Main group'
Params uid label:
zh: '用户ID'
ja: 'ユーザーID'

View File

@@ -18,6 +18,7 @@
uid: "{{ params.uid | int if params.uid | length > 0 else omit }}"
shell: "{{ params.shell if params.shell | length > 0 else omit }}"
home: "{{ params.home if params.home | length > 0 else '/home/' + account.username }}"
group: "{{ params.group if params.group | length > 0 else omit }}"
groups: "{{ params.groups if params.groups | length > 0 else omit }}"
append: "{{ true if params.groups | length > 0 else false }}"
expires: -1

View File

@@ -30,6 +30,12 @@ params:
default: ''
help_text: "{{ 'Params home help text' | trans }}"
- name: group
type: str
label: "{{ 'Params group label' | trans }}"
default: ''
help_text: "{{ 'Params group help text' | trans }}"
- name: groups
type: str
label: "{{ 'Params groups label' | trans }}"
@@ -63,6 +69,11 @@ i18n:
ja: 'デフォルトのホームディレクトリ /home/{アカウントユーザ名}'
en: 'Default home directory /home/{account username}'
Params group help text:
zh: '请输入用户组(名字或数字),只能输入一个(需填写已存在的用户组)'
ja: 'ユーザー グループ (名前または番号) を入力してください。入力できるのは 1 つだけです (既存のユーザー グループを入力する必要があります)'
en: 'Please enter a user group (name or number), only one can be entered (must fill in an existing user group)'
Params groups help text:
zh: '请输入用户组,多个用户组使用逗号分隔(需填写已存在的用户组)'
ja: 'グループを入力してください。複数のグループはコンマで区切ってください(既存のグループを入力してください)'
@@ -88,6 +99,11 @@ i18n:
ja: 'グループ'
en: 'Groups'
Params group label:
zh: '主组'
ja: '主组'
en: 'Main group'
Params uid label:
zh: '用户ID'
ja: 'ユーザーID'

View File

@@ -8,7 +8,7 @@ type:
params:
- name: groups
type: str
label: '用户组'
label: "{{ 'Params groups label' | trans }}"
default: 'Users,Remote Desktop Users'
help_text: "{{ 'Params groups help text' | trans }}"
@@ -24,3 +24,7 @@ i18n:
ja: 'グループを入力してください。複数のグループはコンマで区切ってください(既存のグループを入力してください)'
en: 'Please enter the group. Multiple groups are separated by commas (please enter the existing group)'
Params groups label:
zh: '用户组'
ja: 'グループ'
en: 'Groups'

View File

@@ -9,7 +9,7 @@ type:
params:
- name: groups
type: str
label: '用户组'
label: "{{ 'Params groups label' | trans }}"
default: 'Users,Remote Desktop Users'
help_text: "{{ 'Params groups help text' | trans }}"
@@ -25,3 +25,8 @@ i18n:
ja: 'グループを入力してください。複数のグループはコンマで区切ってください(既存のグループを入力してください)'
en: 'Please enter the group. Multiple groups are separated by commas (please enter the existing group)'
Params groups label:
zh: '用户组'
ja: 'グループ'
en: 'Groups'

View File

@@ -9,7 +9,7 @@ priority: 49
params:
- name: groups
type: str
label: '用户组'
label: "{{ 'Params groups label' | trans }}"
default: 'Users,Remote Desktop Users'
help_text: "{{ 'Params groups help text' | trans }}"
@@ -25,3 +25,8 @@ i18n:
ja: 'グループを入力してください。複数のグループはコンマで区切ってください(既存のグループを入力してください)'
en: 'Please enter the group. Multiple groups are separated by commas (please enter the existing group)'
Params groups label:
zh: '用户组'
ja: 'グループ'
en: 'Groups'

View File

@@ -9,7 +9,7 @@ from accounts.const import (
AutomationTypes, SecretStrategy, ChangeSecretRecordStatusChoice
)
from accounts.models import ChangeSecretRecord
from accounts.notifications import ChangeSecretExecutionTaskMsg, ChangeSecretReportMsg
from accounts.notifications import ChangeSecretExecutionTaskMsg
from accounts.serializers import ChangeSecretRecordBackUpSerializer
from common.utils import get_logger
from common.utils.file import encrypt_and_compress_zip_file
@@ -94,10 +94,6 @@ class ChangeSecretManager(BaseChangeSecretPushManager):
if not recipients:
return
context = self.get_report_context()
for user in recipients:
ChangeSecretReportMsg(user, context).publish()
if not records:
return

View File

@@ -240,6 +240,11 @@ class CheckAccountManager(BaseManager):
print("Check: {} => {}".format(account, msg))
if not error:
AccountRisk.objects.filter(
asset=account.asset,
username=account.username,
risk=handler.risk
).delete()
continue
self.add_risk(handler.risk, account)
self.commit_risks(_assets)

View File

@@ -5,12 +5,14 @@
tasks:
- name: Test SQLServer connection
community.general.mssql_script:
mssql_script:
login_user: "{{ jms_account.username }}"
login_password: "{{ jms_account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
name: '{{ jms_asset.spec_info.db_name }}'
encryption: "{{ jms_asset.encryption | default(None) }}"
tds_version: "{{ jms_asset.tds_version | default(None) }}"
script: |
SELECT
l.name,

View File

@@ -54,3 +54,5 @@
connection_options:
- tlsAllowInvalidHostnames: "{{ jms_asset.spec_info.allow_invalid_cert}}"
when: check_conn_after_change
register: result
failed_when: not result.is_available

View File

@@ -39,7 +39,8 @@
name: "{{ account.username }}"
password: "{{ account.secret }}"
host: "%"
priv: "{{ account.username + '.*:USAGE' if db_name == '' else db_name + '.*:ALL' }}"
priv: "{{ omit if db_name == '' else db_name + '.*:ALL' }}"
append_privs: "{{ db_name != '' | bool }}"
ignore_errors: true
when: db_info is succeeded

View File

@@ -5,12 +5,14 @@
tasks:
- name: Test SQLServer connection
community.general.mssql_script:
mssql_script:
login_user: "{{ jms_account.username }}"
login_password: "{{ jms_account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
name: '{{ jms_asset.spec_info.db_name }}'
encryption: "{{ jms_asset.encryption | default(None) }}"
tds_version: "{{ jms_asset.tds_version | default(None) }}"
script: |
SELECT @@version
register: db_info
@@ -23,47 +25,55 @@
var: info
- name: Check whether SQLServer User exist
community.general.mssql_script:
mssql_script:
login_user: "{{ jms_account.username }}"
login_password: "{{ jms_account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
name: '{{ jms_asset.spec_info.db_name }}'
encryption: "{{ jms_asset.encryption | default(None) }}"
tds_version: "{{ jms_asset.tds_version | default(None) }}"
script: "SELECT 1 from sys.sql_logins WHERE name='{{ account.username }}';"
when: db_info is succeeded
register: user_exist
- name: Change SQLServer password
community.general.mssql_script:
mssql_script:
login_user: "{{ jms_account.username }}"
login_password: "{{ jms_account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
name: '{{ jms_asset.spec_info.db_name }}'
encryption: "{{ jms_asset.encryption | default(None) }}"
tds_version: "{{ jms_asset.tds_version | default(None) }}"
script: "ALTER LOGIN {{ account.username }} WITH PASSWORD = '{{ account.secret }}', DEFAULT_DATABASE = {{ jms_asset.spec_info.db_name }}; select @@version"
ignore_errors: true
when: user_exist.query_results[0] | length != 0
register: change_info
- name: Add SQLServer user
community.general.mssql_script:
mssql_script:
login_user: "{{ jms_account.username }}"
login_password: "{{ jms_account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
name: '{{ jms_asset.spec_info.db_name }}'
encryption: "{{ jms_asset.encryption | default(None) }}"
tds_version: "{{ jms_asset.tds_version | default(None) }}"
script: "CREATE LOGIN [{{ account.username }}] WITH PASSWORD = '{{ account.secret }}'; CREATE USER [{{ account.username }}] FOR LOGIN [{{ account.username }}]; select @@version"
ignore_errors: true
when: user_exist.query_results[0] | length == 0
register: change_info
- name: Verify password
community.general.mssql_script:
mssql_script:
login_user: "{{ account.username }}"
login_password: "{{ account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
name: '{{ jms_asset.spec_info.db_name }}'
encryption: "{{ jms_asset.encryption | default(None) }}"
tds_version: "{{ jms_asset.tds_version | default(None) }}"
script: |
SELECT @@version
when: check_conn_after_change

View File

@@ -18,6 +18,7 @@
uid: "{{ params.uid | int if params.uid | length > 0 else omit }}"
shell: "{{ params.shell if params.shell | length > 0 else omit }}"
home: "{{ params.home if params.home | length > 0 else '/home/' + account.username }}"
group: "{{ params.group if params.group | length > 0 else omit }}"
groups: "{{ params.groups if params.groups | length > 0 else omit }}"
append: "{{ true if params.groups | length > 0 else false }}"
expires: -1

View File

@@ -28,6 +28,12 @@ params:
default: ''
help_text: "{{ 'Params home help text' | trans }}"
- name: group
type: str
label: "{{ 'Params group label' | trans }}"
default: ''
help_text: "{{ 'Params group help text' | trans }}"
- name: groups
type: str
label: "{{ 'Params groups label' | trans }}"
@@ -61,6 +67,11 @@ i18n:
ja: 'デフォルトのホームディレクトリ /home/{アカウントユーザ名}'
en: 'Default home directory /home/{account username}'
Params group help text:
zh: '请输入用户组(名字或数字),只能输入一个(需填写已存在的用户组)'
ja: 'ユーザー グループ (名前または番号) を入力してください。入力できるのは 1 つだけです (既存のユーザー グループを入力する必要があります)'
en: 'Please enter a user group (name or number), only one can be entered (must fill in an existing user group)'
Params groups help text:
zh: '请输入用户组,多个用户组使用逗号分隔(需填写已存在的用户组)'
ja: 'グループを入力してください。複数のグループはコンマで区切ってください(既存のグループを入力してください)'
@@ -86,6 +97,11 @@ i18n:
ja: 'グループ'
en: 'Groups'
Params group label:
zh: '主组'
ja: '主组'
en: 'Main group'
Params uid label:
zh: '用户ID'
ja: 'ユーザーID'

View File

@@ -18,6 +18,7 @@
uid: "{{ params.uid | int if params.uid | length > 0 else omit }}"
shell: "{{ params.shell if params.shell | length > 0 else omit }}"
home: "{{ params.home if params.home | length > 0 else '/home/' + account.username }}"
group: "{{ params.group if params.group | length > 0 else omit }}"
groups: "{{ params.groups if params.groups | length > 0 else omit }}"
append: "{{ true if params.groups | length > 0 else false }}"
expires: -1

View File

@@ -30,6 +30,12 @@ params:
default: ''
help_text: "{{ 'Params home help text' | trans }}"
- name: group
type: str
label: "{{ 'Params group label' | trans }}"
default: ''
help_text: "{{ 'Params group help text' | trans }}"
- name: groups
type: str
label: "{{ 'Params groups label' | trans }}"
@@ -63,6 +69,11 @@ i18n:
ja: 'デフォルトのホームディレクトリ /home/{アカウントユーザ名}'
en: 'Default home directory /home/{account username}'
Params group help text:
zh: '请输入用户组(名字或数字),只能输入一个(需填写已存在的用户组)'
ja: 'ユーザー グループ (名前または番号) を入力してください。入力できるのは 1 つだけです (既存のユーザー グループを入力する必要があります)'
en: 'Please enter a user group (name or number), only one can be entered (must fill in an existing user group)'
Params groups help text:
zh: '请输入用户组,多个用户组使用逗号分隔(需填写已存在的用户组)'
ja: 'グループを入力してください。複数のグループはコンマで区切ってください(既存のグループを入力してください)'
@@ -84,9 +95,14 @@ i18n:
en: 'Home'
Params groups label:
zh: '用户组'
ja: 'グループ'
en: 'Groups'
zh: '附加组'
ja: '追加グループ'
en: 'Additional Group'
Params group label:
zh: '主组'
ja: '主组'
en: 'Main group'
Params uid label:
zh: '用户ID'

View File

@@ -8,7 +8,7 @@ type:
params:
- name: groups
type: str
label: '用户组'
label: "{{ 'Params groups label' | trans }}"
default: 'Users,Remote Desktop Users'
help_text: "{{ 'Params groups help text' | trans }}"
@@ -22,3 +22,8 @@ i18n:
zh: '请输入用户组,多个用户组使用逗号分隔(需填写已存在的用户组)'
ja: 'グループを入力してください。複数のグループはコンマで区切ってください(既存のグループを入力してください)'
en: 'Please enter the group. Multiple groups are separated by commas (please enter the existing group)'
Params groups label:
zh: '用户组'
ja: 'グループ'
en: 'Groups'

View File

@@ -9,7 +9,7 @@ type:
params:
- name: groups
type: str
label: '用户组'
label: "{{ 'Params groups label' | trans }}"
default: 'Users,Remote Desktop Users'
help_text: "{{ 'Params groups help text' | trans }}"
@@ -23,3 +23,8 @@ i18n:
zh: '请输入用户组,多个用户组使用逗号分隔(需填写已存在的用户组)'
ja: 'グループを入力してください。複数のグループはコンマで区切ってください(既存のグループを入力してください)'
en: 'Please enter the group. Multiple groups are separated by commas (please enter the existing group)'
Params groups label:
zh: '用户组'
ja: 'グループ'
en: 'Groups'

View File

@@ -9,7 +9,7 @@ priority: 49
params:
- name: groups
type: str
label: '用户组'
label: "{{ 'Params groups label' | trans }}"
default: 'Users,Remote Desktop Users'
help_text: "{{ 'Params groups help text' | trans }}"
@@ -23,3 +23,8 @@ i18n:
zh: '请输入用户组,多个用户组使用逗号分隔(需填写已存在的用户组)'
ja: 'グループを入力してください。複数のグループはコンマで区切ってください(既存のグループを入力してください)'
en: 'Please enter the group. Multiple groups are separated by commas (please enter the existing group)'
Params groups label:
zh: '用户组'
ja: 'グループ'
en: 'Groups'

View File

@@ -5,11 +5,13 @@
tasks:
- name: "Remove account"
community.general.mssql_script:
mssql_script:
login_user: "{{ jms_account.username }}"
login_password: "{{ jms_account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
name: "{{ jms_asset.spec_info.db_name }}"
encryption: "{{ jms_asset.encryption | default(None) }}"
tds_version: "{{ jms_asset.tds_version | default(None) }}"
script: "DROP LOGIN {{ account.username }}; select @@version"

View File

@@ -16,3 +16,5 @@
ssl_certfile: "{{ jms_asset.secret_info.client_key | default('') }}"
connection_options:
- tlsAllowInvalidHostnames: "{{ jms_asset.spec_info.allow_invalid_cert }}"
register: result
failed_when: not result.is_available

View File

@@ -5,11 +5,13 @@
tasks:
- name: Verify account
community.general.mssql_script:
mssql_script:
login_user: "{{ account.username }}"
login_password: "{{ account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
name: '{{ jms_asset.spec_info.db_name }}'
encryption: "{{ jms_asset.encryption | default(None) }}"
tds_version: "{{ jms_asset.tds_version | default(None) }}"
script: |
SELECT @@version

View File

@@ -1,8 +1,5 @@
# -*- coding: utf-8 -*-
#
from azure.core.exceptions import ResourceNotFoundError, ClientAuthenticationError
from azure.identity import ClientSecretCredential
from azure.keyvault.secrets import SecretClient
from common.utils import get_logger
@@ -14,6 +11,9 @@ __all__ = ['AZUREVaultClient']
class AZUREVaultClient(object):
def __init__(self, vault_url, tenant_id, client_id, client_secret):
from azure.identity import ClientSecretCredential
from azure.keyvault.secrets import SecretClient
authentication_endpoint = 'https://login.microsoftonline.com/' \
if ('azure.net' in vault_url) else 'https://login.chinacloudapi.cn/'
@@ -23,6 +23,8 @@ class AZUREVaultClient(object):
self.client = SecretClient(vault_url=vault_url, credential=credentials)
def is_active(self):
from azure.core.exceptions import ResourceNotFoundError, ClientAuthenticationError
try:
self.client.set_secret('jumpserver', '666')
except (ResourceNotFoundError, ClientAuthenticationError) as e:
@@ -32,6 +34,8 @@ class AZUREVaultClient(object):
return True, ''
def get(self, name, version=None):
from azure.core.exceptions import ResourceNotFoundError, ClientAuthenticationError
try:
secret = self.client.get_secret(name, version)
return secret.value

View File

@@ -46,11 +46,16 @@ class Migration(migrations.Migration):
],
options={
'verbose_name': 'Account',
'permissions': [('view_accountsecret', 'Can view asset account secret'),
('view_historyaccount', 'Can view asset history account'),
('view_historyaccountsecret', 'Can view asset history account secret'),
('verify_account', 'Can verify account'), ('push_account', 'Can push account'),
('remove_account', 'Can remove account')],
'permissions': [
('view_accountsecret', 'Can view asset account secret'),
('view_historyaccount', 'Can view asset history account'),
('view_historyaccountsecret', 'Can view asset history account secret'),
('verify_account', 'Can verify account'),
('push_account', 'Can push account'),
('remove_account', 'Can remove account'),
('view_accountsession', 'Can view session'),
('view_accountactivity', 'Can view activity')
],
},
),
migrations.CreateModel(

View File

@@ -116,6 +116,8 @@ class Account(AbsConnectivity, LabeledMixin, BaseAccount, JSONFilterMixin):
('verify_account', _('Can verify account')),
('push_account', _('Can push account')),
('remove_account', _('Can remove account')),
('view_accountsession', _('Can view session')),
('view_accountactivity', _('Can view activity')),
]
def __str__(self):
@@ -130,7 +132,7 @@ class Account(AbsConnectivity, LabeledMixin, BaseAccount, JSONFilterMixin):
return self.asset.platform
@lazyproperty
def alias(self):
def alias(self) -> str:
"""
别称,因为有虚拟账号,@INPUT @MANUAL @USER, 否则为 id
"""
@@ -138,13 +140,13 @@ class Account(AbsConnectivity, LabeledMixin, BaseAccount, JSONFilterMixin):
return self.username
return str(self.id)
def is_virtual(self):
def is_virtual(self) -> bool:
"""
不要用 username 去判断,因为可能是构造的 account 对象,设置了同名账号的用户名,
"""
return self.alias.startswith('@')
def is_ds_account(self):
def is_ds_account(self) -> bool:
if self.is_virtual():
return ''
if not self.asset.is_directory_service:
@@ -158,7 +160,7 @@ class Account(AbsConnectivity, LabeledMixin, BaseAccount, JSONFilterMixin):
return self.asset.ds
@lazyproperty
def ds_domain(self):
def ds_domain(self) -> str:
"""这个不能去掉perm_account 会动态设置这个值,以更改 full_username"""
if self.is_virtual():
return ''
@@ -170,17 +172,17 @@ class Account(AbsConnectivity, LabeledMixin, BaseAccount, JSONFilterMixin):
return '@' in self.username or '\\' in self.username
@property
def full_username(self):
def full_username(self) -> str:
if not self.username_has_domain() and self.ds_domain:
return '{}@{}'.format(self.username, self.ds_domain)
return self.username
@lazyproperty
def has_secret(self):
def has_secret(self) -> bool:
return bool(self.secret)
@lazyproperty
def versions(self):
def versions(self) -> int:
return self.history.count()
def get_su_from_accounts(self):

View File

@@ -33,7 +33,7 @@ class IntegrationApplication(JMSOrgBaseModel):
return qs.filter(*query)
@property
def accounts_amount(self):
def accounts_amount(self) -> int:
return self.get_accounts().count()
@property

View File

@@ -68,8 +68,10 @@ class AccountRisk(JMSOrgBaseModel):
related_name='risks', null=True
)
risk = models.CharField(max_length=128, verbose_name=_('Risk'), choices=RiskChoice.choices)
status = models.CharField(max_length=32, choices=ConfirmOrIgnore.choices, default=ConfirmOrIgnore.pending,
blank=True, verbose_name=_('Status'))
status = models.CharField(
max_length=32, choices=ConfirmOrIgnore.choices, default=ConfirmOrIgnore.pending,
blank=True, verbose_name=_('Status')
)
details = models.JSONField(default=list, verbose_name=_('Detail'))
class Meta:

View File

@@ -75,11 +75,11 @@ class BaseAccount(VaultModelMixin, JMSOrgBaseModel):
return bool(self.secret)
@property
def has_username(self):
def has_username(self) -> bool:
return bool(self.username)
@property
def spec_info(self):
def spec_info(self) -> dict:
data = {}
if self.secret_type != SecretType.SSH_KEY:
return data
@@ -87,13 +87,13 @@ class BaseAccount(VaultModelMixin, JMSOrgBaseModel):
return data
@property
def password(self):
def password(self) -> str:
if self.secret_type == SecretType.PASSWORD:
return self.secret
return None
@property
def private_key(self):
def private_key(self) -> str:
if self.secret_type == SecretType.SSH_KEY:
return self.secret
return None
@@ -110,7 +110,7 @@ class BaseAccount(VaultModelMixin, JMSOrgBaseModel):
return None
@property
def ssh_key_fingerprint(self):
def ssh_key_fingerprint(self) -> str:
if self.public_key:
public_key = self.public_key
elif self.private_key:

View File

@@ -56,7 +56,7 @@ class VaultModelMixin(models.Model):
__secret = None
@property
def secret(self):
def secret(self) -> str:
if self.__secret:
return self.__secret
from accounts.backends import vault_client

View File

@@ -18,11 +18,11 @@ class VirtualAccount(JMSOrgBaseModel):
verbose_name = _('Virtual account')
@property
def name(self):
def name(self) -> str:
return self.get_alias_display()
@property
def username(self):
def username(self) -> str:
usernames_map = {
AliasAccount.INPUT: _("Manual input"),
AliasAccount.USER: _("Same with user"),
@@ -32,7 +32,7 @@ class VirtualAccount(JMSOrgBaseModel):
return usernames_map.get(self.alias, '')
@property
def comment(self):
def comment(self) -> str:
comments_map = {
AliasAccount.INPUT: _('Non-asset account, Input username/password on connect'),
AliasAccount.USER: _('The account username name same with user on connect'),

View File

@@ -14,7 +14,7 @@ from accounts.models import Account, AccountTemplate, GatheredAccount
from accounts.tasks import push_accounts_to_assets_task
from assets.const import Category, AllTypes
from assets.models import Asset
from common.serializers import SecretReadableMixin
from common.serializers import SecretReadableMixin, CommonBulkModelSerializer
from common.serializers.fields import ObjectRelatedField, LabeledChoiceField
from common.utils import get_logger
from .base import BaseAccountSerializer, AuthValidateMixin
@@ -253,6 +253,8 @@ class AccountSerializer(AccountCreateUpdateSerializerMixin, BaseAccountSerialize
'source_id': {'required': False, 'allow_null': True},
}
fields_unimport_template = ['params']
# 手动判断唯一性校验
validators = []
@classmethod
def setup_eager_loading(cls, queryset):
@@ -263,6 +265,21 @@ class AccountSerializer(AccountCreateUpdateSerializerMixin, BaseAccountSerialize
)
return queryset
def validate(self, attrs):
instance = getattr(self, "instance", None)
if instance:
return super().validate(attrs)
field_errors = {}
for _fields in Account._meta.unique_together:
lookup = {field: attrs.get(field) for field in _fields}
if Account.objects.filter(**lookup).exists():
verbose_names = ', '.join([str(Account._meta.get_field(f).verbose_name) for f in _fields])
msg_template = _('Account already exists. Field(s): {fields} must be unique.')
field_errors[_fields[0]] = msg_template.format(fields=verbose_names)
raise serializers.ValidationError(field_errors)
return attrs
class AccountDetailSerializer(AccountSerializer):
has_secret = serializers.BooleanField(label=_("Has secret"), read_only=True)
@@ -275,26 +292,26 @@ class AccountDetailSerializer(AccountSerializer):
class AssetAccountBulkSerializerResultSerializer(serializers.Serializer):
asset = serializers.CharField(read_only=True, label=_('Asset'))
account = serializers.CharField(read_only=True, label=_('Account'))
state = serializers.CharField(read_only=True, label=_('State'))
error = serializers.CharField(read_only=True, label=_('Error'))
changed = serializers.BooleanField(read_only=True, label=_('Changed'))
class AssetAccountBulkSerializer(
AccountCreateUpdateSerializerMixin, AuthValidateMixin, serializers.ModelSerializer
AccountCreateUpdateSerializerMixin, AuthValidateMixin, CommonBulkModelSerializer
):
su_from_username = serializers.CharField(
max_length=128, required=False, write_only=True, allow_null=True, label=_("Su from"),
allow_blank=True,
)
assets = serializers.PrimaryKeyRelatedField(queryset=Asset.objects, many=True, label=_('Assets'))
class Meta:
model = Account
fields = [
'name', 'username', 'secret', 'secret_type', 'passphrase',
'privileged', 'is_active', 'comment', 'template',
'on_invalid', 'push_now', 'params', 'assets',
'name', 'username', 'secret', 'secret_type', 'secret_reset',
'passphrase', 'privileged', 'is_active', 'comment', 'template',
'on_invalid', 'push_now', 'params',
'su_from_username', 'source', 'source_id',
]
extra_kwargs = {
@@ -376,8 +393,7 @@ class AssetAccountBulkSerializer(
handler = self._handle_err_create
return handler
def perform_bulk_create(self, vd):
assets = vd.pop('assets')
def perform_bulk_create(self, vd, assets):
on_invalid = vd.pop('on_invalid', 'skip')
secret_type = vd.get('secret_type', 'password')
@@ -385,8 +401,7 @@ class AssetAccountBulkSerializer(
vd['name'] = vd.get('username')
create_handler = self.get_create_handler(on_invalid)
asset_ids = [asset.id for asset in assets]
secret_type_supports = Asset.get_secret_type_assets(asset_ids, secret_type)
secret_type_supports = Asset.get_secret_type_assets(assets, secret_type)
_results = {}
for asset in assets:
@@ -394,6 +409,7 @@ class AssetAccountBulkSerializer(
_results[asset] = {
'error': _('Asset does not support this secret type: %s') % secret_type,
'state': 'error',
'account': vd['name'],
}
continue
@@ -403,13 +419,13 @@ class AssetAccountBulkSerializer(
self.clean_auth_fields(vd)
instance, changed, state = self.perform_create(vd, create_handler)
_results[asset] = {
'changed': changed, 'instance': instance.id, 'state': state
'changed': changed, 'instance': instance.id, 'state': state, 'account': vd['name']
}
except serializers.ValidationError as e:
_results[asset] = {'error': e.detail[0], 'state': 'error'}
_results[asset] = {'error': e.detail[0], 'state': 'error', 'account': vd['name']}
except Exception as e:
logger.exception(e)
_results[asset] = {'error': str(e), 'state': 'error'}
_results[asset] = {'error': str(e), 'state': 'error', 'account': vd['name']}
results = [{'asset': asset, **result} for asset, result in _results.items()]
state_score = {'created': 3, 'updated': 2, 'skipped': 1, 'error': 0}
@@ -426,7 +442,8 @@ class AssetAccountBulkSerializer(
errors.append({
'error': _('Account has exist'),
'state': 'error',
'asset': str(result['asset'])
'asset': str(result['asset']),
'account': result.get('account'),
})
if errors:
raise serializers.ValidationError(errors)
@@ -445,10 +462,16 @@ class AssetAccountBulkSerializer(
account_ids = [str(_id) for _id in accounts.values_list('id', flat=True)]
push_accounts_to_assets_task.delay(account_ids, params)
def create(self, validated_data):
def bulk_create(self, validated_data, assets):
if not assets:
raise serializers.ValidationError(
{'assets': _('At least one asset or node must be specified')},
{'nodes': _('At least one asset or node must be specified')}
)
params = validated_data.pop('params', None)
push_now = validated_data.pop('push_now', False)
results = self.perform_bulk_create(validated_data)
results = self.perform_bulk_create(validated_data, assets)
self.push_accounts_if_need(results, push_now, params)
for res in results:
res['asset'] = str(res['asset'])
@@ -456,6 +479,8 @@ class AssetAccountBulkSerializer(
class AccountSecretSerializer(SecretReadableMixin, AccountSerializer):
spec_info = serializers.DictField(label=_('Spec info'), read_only=True)
class Meta(AccountSerializer.Meta):
fields = AccountSerializer.Meta.fields + ['spec_info']
extra_kwargs = {
@@ -470,6 +495,7 @@ class AccountSecretSerializer(SecretReadableMixin, AccountSerializer):
class AccountHistorySerializer(serializers.ModelSerializer):
secret_type = LabeledChoiceField(choices=SecretType.choices, label=_('Secret type'))
secret = serializers.CharField(label=_('Secret'), read_only=True)
id = serializers.IntegerField(label=_('ID'), source='history_id', read_only=True)
class Meta:

View File

@@ -70,6 +70,8 @@ class AuthValidateMixin(serializers.Serializer):
class BaseAccountSerializer(
AuthValidateMixin, ResourceLabelsMixin, BulkOrgResourceModelSerializer
):
spec_info = serializers.DictField(label=_('Spec info'), read_only=True)
class Meta:
model = BaseAccount
fields_mini = ["id", "name", "username"]

View File

@@ -130,7 +130,7 @@ class ChangeSecretRecordSerializer(serializers.ModelSerializer):
read_only_fields = fields
@staticmethod
def get_is_success(obj):
def get_is_success(obj) -> bool:
return obj.status == ChangeSecretRecordStatusChoice.success
@@ -157,7 +157,7 @@ class ChangeSecretRecordBackUpSerializer(serializers.ModelSerializer):
read_only_fields = fields
@staticmethod
def get_asset(instance):
def get_asset(instance) -> str:
return str(instance.asset)
@staticmethod
@@ -165,7 +165,7 @@ class ChangeSecretRecordBackUpSerializer(serializers.ModelSerializer):
return str(instance.account)
@staticmethod
def get_is_success(obj):
def get_is_success(obj) -> str:
if obj.status == ChangeSecretRecordStatusChoice.success.value:
return _("Success")
return _("Failed")
@@ -196,9 +196,9 @@ class ChangeSecretAccountSerializer(serializers.ModelSerializer):
read_only_fields = fields
@staticmethod
def get_meta(obj):
def get_meta(obj) -> dict:
return account_secret_task_status.get(str(obj.id))
@staticmethod
def get_ttl(obj):
def get_ttl(obj) -> int:
return account_secret_task_status.get_ttl(str(obj.id))

View File

@@ -69,7 +69,7 @@ class AssetRiskSerializer(serializers.Serializer):
risk_summary = serializers.SerializerMethodField()
@staticmethod
def get_risk_summary(obj):
def get_risk_summary(obj) -> dict:
summary = {}
for risk in RiskChoice.choices:
summary[f"{risk[0]}_count"] = obj.get(f"{risk[0]}_count", 0)

View File

@@ -1,36 +0,0 @@
{% load i18n %}
<h3>{% trans 'Task name' %}: {{ name }}</h3>
<h3>{% trans 'Task execution id' %}: {{ execution_id }}</h3>
<p>{% trans 'Respectful' %} {{ recipient }}</p>
<p>{% trans 'Hello! The following is the failure of changing the password of your assets or pushing the account. Please check and handle it in time.' %}</p>
<table style="width: 100%; border-collapse: collapse; max-width: 100%; text-align: left; margin-top: 20px;">
<caption></caption>
<thead>
<tr style="background-color: #f2f2f2;">
<th style="border: 1px solid #ddd; padding: 10px;">{% trans 'Asset' %}</th>
<th style="border: 1px solid #ddd; padding: 10px;">{% trans 'Account' %}</th>
<th style="border: 1px solid #ddd; padding: 10px;">{% trans 'Error' %}</th>
</tr>
</thead>
<tbody>
{% for asset_name, account_username, error in asset_account_errors %}
<tr>
<td style="border: 1px solid #ddd; padding: 10px;">{{ asset_name }}</td>
<td style="border: 1px solid #ddd; padding: 10px;">{{ account_username }}</td>
<td style="border: 1px solid #ddd; padding: 10px;">
<div style="
max-width: 90%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
display: block;"
title="{{ error }}"
>
{{ error }}
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>

View File

@@ -3,3 +3,4 @@ from .connect_method import *
from .login_acl import *
from .login_asset_acl import *
from .login_asset_check import *
from .data_masking import *

View File

@@ -0,0 +1,20 @@
from orgs.mixins.api import OrgBulkModelViewSet
from .common import ACLUserFilterMixin
from ..models import DataMaskingRule
from .. import serializers
__all__ = ['DataMaskingRuleViewSet']
class DataMaskingRuleFilter(ACLUserFilterMixin):
class Meta:
model = DataMaskingRule
fields = ('name',)
class DataMaskingRuleViewSet(OrgBulkModelViewSet):
model = DataMaskingRule
filterset_class = DataMaskingRuleFilter
search_fields = ('name',)
serializer_class = serializers.DataMaskingRuleSerializer

View File

@@ -8,7 +8,7 @@ __all__ = ['LoginAssetACLViewSet']
class LoginAssetACLFilter(ACLUserAssetFilterMixin):
class Meta:
model = models.LoginAssetACL
fields = ['name', ]
fields = ['name', 'action']
class LoginAssetACLViewSet(OrgBulkModelViewSet):

View File

@@ -0,0 +1,45 @@
# Generated by Django 4.1.13 on 2025-10-07 16:16
import common.db.fields
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('acls', '0002_auto_20210926_1047'),
]
operations = [
migrations.CreateModel(
name='DataMaskingRule',
fields=[
('created_by', models.CharField(blank=True, max_length=128, null=True, verbose_name='Created by')),
('updated_by', models.CharField(blank=True, max_length=128, null=True, verbose_name='Updated by')),
('date_created', models.DateTimeField(auto_now_add=True, null=True, verbose_name='Date created')),
('date_updated', models.DateTimeField(auto_now=True, verbose_name='Date updated')),
('comment', models.TextField(blank=True, default='', verbose_name='Comment')),
('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)),
('org_id', models.CharField(blank=True, db_index=True, default='', max_length=36, verbose_name='Organization')),
('priority', models.IntegerField(default=50, help_text='1-100, the lower the value will be match first', validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(100)], verbose_name='Priority')),
('action', models.CharField(default='reject', max_length=64, verbose_name='Action')),
('is_active', models.BooleanField(default=True, verbose_name='Active')),
('users', common.db.fields.JSONManyToManyField(default=dict, to='users.User', verbose_name='Users')),
('assets', common.db.fields.JSONManyToManyField(default=dict, to='assets.Asset', verbose_name='Assets')),
('accounts', models.JSONField(default=list, verbose_name='Accounts')),
('name', models.CharField(max_length=128, verbose_name='Name')),
('fields_pattern', models.CharField(default='password', max_length=128, verbose_name='Fields pattern')),
('masking_method', models.CharField(choices=[('fixed_char', 'Fixed Character Replacement'), ('hide_middle', 'Hide Middle Characters'), ('keep_prefix', 'Keep Prefix Only'), ('keep_suffix', 'Keep Suffix Only')], default='fixed_char', max_length=32, verbose_name='Masking Method')),
('mask_pattern', models.CharField(blank=True, default='######', max_length=128, null=True, verbose_name='Mask Pattern')),
('reviewers', models.ManyToManyField(blank=True, to=settings.AUTH_USER_MODEL, verbose_name='Reviewers')),
],
options={
'verbose_name': 'Data Masking Rule',
'unique_together': {('org_id', 'name')},
},
),
]

View File

@@ -2,3 +2,4 @@ from .command_acl import *
from .connect_method import *
from .login_acl import *
from .login_asset_acl import *
from .data_masking import *

View File

@@ -5,7 +5,7 @@ from django.utils.translation import gettext_lazy as _
from common.db.fields import JSONManyToManyField
from common.db.models import JMSBaseModel
from common.utils import contains_ip
from common.utils.time_period import contains_time_period
from common.utils.timezone import contains_time_period
from orgs.mixins.models import OrgModelMixin, OrgManager
from ..const import ActionChoices

View File

@@ -34,16 +34,16 @@ class CommandGroup(JMSOrgBaseModel):
@lazyproperty
def pattern(self):
content = self.content.replace('\r\n', '\n')
if self.type == 'command':
s = self.construct_command_regex(self.content)
s = self.construct_command_regex(content)
else:
s = r'{0}'.format(self.content)
s = r'{0}'.format(r'{}'.format('|'.join(content.split('\n'))))
return s
@classmethod
def construct_command_regex(cls, content):
regex = []
content = content.replace('\r\n', '\n')
for _cmd in content.split('\n'):
cmd = re.sub(r'\s+', ' ', _cmd)
cmd = re.escape(cmd)

View File

@@ -0,0 +1,42 @@
from django.db import models
from acls.models import UserAssetAccountBaseACL
from common.utils import get_logger
from django.utils.translation import gettext_lazy as _
logger = get_logger(__file__)
__all__ = ['MaskingMethod', 'DataMaskingRule']
class MaskingMethod(models.TextChoices):
fixed_char = "fixed_char", _("Fixed Character Replacement") # 固定字符替换
hide_middle = "hide_middle", _("Hide Middle Characters") # 隐藏中间几位
keep_prefix = "keep_prefix", _("Keep Prefix Only") # 只保留前缀
keep_suffix = "keep_suffix", _("Keep Suffix Only") # 只保留后缀
class DataMaskingRule(UserAssetAccountBaseACL):
name = models.CharField(max_length=128, verbose_name=_("Name"))
fields_pattern = models.CharField(max_length=128, default='password', verbose_name=_("Fields pattern"))
masking_method = models.CharField(
max_length=32,
choices=MaskingMethod.choices,
default=MaskingMethod.fixed_char,
verbose_name=_("Masking Method"),
)
mask_pattern = models.CharField(
max_length=128,
verbose_name=_("Mask Pattern"),
default="######",
blank=True,
null=True,
)
def __str__(self):
return self.name
class Meta:
unique_together = [('org_id', 'name')]
verbose_name = _("Data Masking Rule")

View File

@@ -1,30 +1,52 @@
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from accounts.models import Account
from acls.models import LoginACL, LoginAssetACL
from assets.models import Asset
from audits.models import UserLoginLog
from common.views.template import custom_render_to_string
from notifications.notifications import UserMessage
from users.models import User
class UserLoginReminderMsg(UserMessage):
subject = _('User login reminder')
template_name = 'acls/user_login_reminder.html'
contexts = [
{"name": "city", "label": _('Login city'), "default": "Shanghai"},
{"name": "username", "label": _('User'), "default": "john"},
{"name": "ip", "label": "IP", "default": "192.168.1.1"},
{"name": "recipient_name", "label": _("Recipient name"), "default": "John"},
{"name": "recipient_username", "label": _("Recipient username"), "default": "john"},
{"name": "user_agent", "label": _('User agent'), "default": "Mozilla/5.0"},
{"name": "acl_name", "label": _('ACL name'), "default": "login acl"},
{"name": "login_from", "label": _('Login from'), "default": "web"},
{"name": "time", "label": _('Login time'), "default": "2025-01-01 12:00:00"},
]
def __init__(self, user, user_log: UserLoginLog):
def __init__(self, user, user_log: UserLoginLog, acl: LoginACL):
self.user_log = user_log
self.acl_name = str(acl)
self.login_from = user_log.get_type_display()
now = timezone.localtime(user_log.datetime)
self.time = now.strftime('%Y-%m-%d %H:%M:%S')
super().__init__(user)
def get_html_msg(self) -> dict:
user_log = self.user_log
context = {
'ip': user_log.ip,
'time': self.time,
'city': user_log.city,
'acl_name': self.acl_name,
'login_from': self.login_from,
'username': user_log.username,
'recipient': self.user,
'recipient_name': self.user.name,
'recipient_username': self.user.username,
'user_agent': user_log.user_agent,
}
message = render_to_string('acls/user_login_reminder.html', context)
message = custom_render_to_string(self.template_name, context)
return {
'subject': str(self.subject),
@@ -40,24 +62,55 @@ class UserLoginReminderMsg(UserMessage):
class AssetLoginReminderMsg(UserMessage):
subject = _('User login alert for asset')
template_name = 'acls/asset_login_reminder.html'
contexts = [
{"name": "city", "label": _('Login city'), "default": "Shanghai"},
{"name": "username", "label": _('User'), "default": "john"},
{"name": "name", "label": _('Name'), "default": "John"},
{"name": "asset", "label": _('Asset'), "default": "dev server"},
{"name": "recipient_name", "label": _('Recipient name'), "default": "John"},
{"name": "recipient_username", "label": _('Recipient username'), "default": "john"},
{"name": "account", "label": _('Account Input username'), "default": "root"},
{"name": "account_name", "label": _('Account name'), "default": "root"},
{"name": "acl_name", "label": _('ACL name'), "default": "login acl"},
{"name": "ip", "label": "IP", "default": "192.168.1.1"},
{"name": "login_from", "label": _('Login from'), "default": "web"},
{"name": "time", "label": _('Login time'), "default": "2025-01-01 12:00:00"}
]
def __init__(self, user, asset: Asset, login_user: User, account: Account, input_username):
def __init__(
self, user, asset: Asset, login_user: User,
account: Account, acl: LoginAssetACL,
ip, input_username, login_from
):
self.ip = ip
self.asset = asset
self.login_user = login_user
self.account = account
self.acl_name = str(acl)
self.login_from = login_from
self.login_user = login_user
self.input_username = input_username
now = timezone.localtime(timezone.now())
self.time = now.strftime('%Y-%m-%d %H:%M:%S')
super().__init__(user)
def get_html_msg(self) -> dict:
context = {
'recipient': self.user,
'ip': self.ip,
'time': self.time,
'login_from': self.login_from,
'recipient_name': self.user.name,
'recipient_username': self.user.username,
'username': self.login_user.username,
'name': self.login_user.name,
'asset': str(self.asset),
'account': self.input_username,
'account_name': self.account.name,
'acl_name': self.acl_name,
}
message = render_to_string('acls/asset_login_reminder.html', context)
message = custom_render_to_string(self.template_name, context)
return {
'subject': str(self.subject),

View File

@@ -3,3 +3,4 @@ from .connect_method import *
from .login_acl import *
from .login_asset_acl import *
from .login_asset_check import *
from .data_masking import *

View File

@@ -90,7 +90,7 @@ class BaseACLSerializer(ActionAclSerializer, serializers.Serializer):
fields_small = fields_mini + [
"is_active", "priority", "action",
"date_created", "date_updated",
"comment", "created_by", "org_id",
"comment", "created_by"
]
fields_m2m = ["reviewers", ]
fields = fields_small + fields_m2m
@@ -100,6 +100,20 @@ class BaseACLSerializer(ActionAclSerializer, serializers.Serializer):
'reviewers': {'label': _('Recipients')},
}
class BaseUserACLSerializer(BaseACLSerializer):
users = JSONManyToManyField(label=_('User'))
class Meta(BaseACLSerializer.Meta):
fields = BaseACLSerializer.Meta.fields + ['users']
class BaseUserAssetAccountACLSerializer(BaseUserACLSerializer):
assets = JSONManyToManyField(label=_('Asset'))
accounts = serializers.ListField(label=_('Account'))
class Meta(BaseUserACLSerializer.Meta):
fields = BaseUserACLSerializer.Meta.fields + ['assets', 'accounts', 'org_id']
def validate_reviewers(self, reviewers):
action = self.initial_data.get('action')
if not action and self.instance:
@@ -118,19 +132,4 @@ class BaseACLSerializer(ActionAclSerializer, serializers.Serializer):
"None of the reviewers belong to Organization `{}`".format(org.name)
)
raise serializers.ValidationError(error)
return valid_reviewers
class BaseUserACLSerializer(BaseACLSerializer):
users = JSONManyToManyField(label=_('User'))
class Meta(BaseACLSerializer.Meta):
fields = BaseACLSerializer.Meta.fields + ['users']
class BaseUserAssetAccountACLSerializer(BaseUserACLSerializer):
assets = JSONManyToManyField(label=_('Asset'))
accounts = serializers.ListField(label=_('Account'))
class Meta(BaseUserACLSerializer.Meta):
fields = BaseUserACLSerializer.Meta.fields + ['assets', 'accounts']
return valid_reviewers

View File

@@ -1,4 +1,4 @@
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
from common.serializers.mixin import CommonBulkModelSerializer
from .base import BaseUserAssetAccountACLSerializer as BaseSerializer
from ..const import ActionChoices
from ..models import ConnectMethodACL
@@ -6,16 +6,15 @@ from ..models import ConnectMethodACL
__all__ = ["ConnectMethodACLSerializer"]
class ConnectMethodACLSerializer(BaseSerializer, BulkOrgResourceModelSerializer):
class ConnectMethodACLSerializer(BaseSerializer, CommonBulkModelSerializer):
class Meta(BaseSerializer.Meta):
model = ConnectMethodACL
fields = [
i for i in BaseSerializer.Meta.fields + ['connect_methods']
if i not in ['assets', 'accounts']
if i not in ['assets', 'accounts', 'org_id']
]
action_choices_exclude = BaseSerializer.Meta.action_choices_exclude + [
ActionChoices.review,
ActionChoices.accept,
ActionChoices.notice,
ActionChoices.face_verify,
ActionChoices.face_online,

View File

@@ -0,0 +1,19 @@
from django.utils.translation import gettext_lazy as _
from acls.models import MaskingMethod, DataMaskingRule
from common.serializers.fields import LabeledChoiceField
from common.serializers.mixin import CommonBulkModelSerializer
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
from .base import BaseUserAssetAccountACLSerializer as BaseSerializer
__all__ = ['DataMaskingRuleSerializer']
class DataMaskingRuleSerializer(BaseSerializer, BulkOrgResourceModelSerializer):
masking_method = LabeledChoiceField(
choices=MaskingMethod.choices, default=MaskingMethod.fixed_char, label=_('Masking Method')
)
class Meta(BaseSerializer.Meta):
model = DataMaskingRule
fields = BaseSerializer.Meta.fields + ['fields_pattern', 'masking_method', 'mask_pattern']

View File

@@ -1,7 +1,7 @@
from django.utils.translation import gettext as _
from common.serializers import CommonBulkModelSerializer
from common.serializers import MethodSerializer
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
from .base import BaseUserACLSerializer
from .rules import RuleSerializer
from ..const import ActionChoices
@@ -12,12 +12,12 @@ __all__ = ["LoginACLSerializer"]
common_help_text = _("With * indicating a match all. ")
class LoginACLSerializer(BaseUserACLSerializer, BulkOrgResourceModelSerializer):
class LoginACLSerializer(BaseUserACLSerializer, CommonBulkModelSerializer):
rules = MethodSerializer(label=_('Rule'))
class Meta(BaseUserACLSerializer.Meta):
model = LoginACL
fields = BaseUserACLSerializer.Meta.fields + ['rules', ]
fields = list((set(BaseUserACLSerializer.Meta.fields) | {'rules'}))
action_choices_exclude = [
ActionChoices.warning,
ActionChoices.notify_and_warn,

View File

@@ -1,13 +1,17 @@
{% load i18n %}
<h3>{% trans 'Dear' %}: {{ recipient.name }}[{{ recipient.username }}]</h3>
<h3>{% trans 'Dear' %}: {{ recipient_name }}[{{ recipient_username }}]</h3>
<hr>
<p>{% trans 'We would like to inform you that a user has recently logged into the following asset:' %}<p>
<p><strong>{% trans 'Asset details' %}:</strong></p>
<ul>
<li><strong>{% trans 'User' %}:</strong> [{{ name }}({{ username }})]</li>
<li><strong>IP:</strong> [{{ ip }}]</li>
<li><strong>{% trans 'Assets' %}:</strong> [{{ asset }}]</li>
<li><strong>{% trans 'Account' %}:</strong> [{{ account_name }}({{ account }})]</li>
<li><strong>{% trans 'Login asset acl' %}:</strong> [{{ acl_name }}]</li>
<li><strong>{% trans 'Login from' %}:</strong> [{{ login_from }}]</li>
<li><strong>{% trans 'Time' %}:</strong> [{{ time }}]</li>
</ul>
<hr>

View File

@@ -1,6 +1,6 @@
{% load i18n %}
<h3>{% trans 'Dear' %}: {{ recipient.name }}[{{ recipient.username }}]</h3>
<h3>{% trans 'Dear' %}: {{ recipient_name }}[{{ recipient_username }}]</h3>
<hr>
<p>{% trans 'We would like to inform you that a user has recently logged:' %}<p>
<p><strong>{% trans 'User details' %}:</strong></p>
@@ -8,7 +8,10 @@
<li><strong>{% trans 'User' %}:</strong> [{{ username }}]</li>
<li><strong>IP:</strong> [{{ ip }}]</li>
<li><strong>{% trans 'Login city' %}:</strong> [{{ city }}]</li>
<li><strong>{% trans 'Login from' %}:</strong> [{{ login_from }}]</li>
<li><strong>{% trans 'User agent' %}:</strong> [{{ user_agent }}]</li>
<li><strong>{% trans 'Login acl' %}:</strong> [{{ acl_name }}]</li>
<li><strong>{% trans 'Time' %}:</strong> [{{ time }}]</li>
</ul>
<hr>

View File

@@ -11,6 +11,7 @@ router.register(r'login-asset-acls', api.LoginAssetACLViewSet, 'login-asset-acl'
router.register(r'command-filter-acls', api.CommandFilterACLViewSet, 'command-filter-acl')
router.register(r'command-groups', api.CommandGroupViewSet, 'command-group')
router.register(r'connect-method-acls', api.ConnectMethodACLViewSet, 'connect-method-acl')
router.register(r'data-masking-rules', api.DataMaskingRuleViewSet, 'data-masking-rule')
urlpatterns = [
path('login-asset/check/', api.LoginAssetCheckAPI.as_view(), name='login-asset-check'),

View File

@@ -1,8 +1,7 @@
# -*- coding: utf-8 -*-
#
from collections import defaultdict
from django.conf import settings
from django.db import transaction
from django.shortcuts import get_object_or_404
from django.utils.translation import gettext as _
from django_filters import rest_framework as drf_filters
@@ -113,7 +112,7 @@ class BaseAssetViewSet(OrgBulkModelViewSet):
("accounts", AccountSerializer),
)
rbac_perms = (
("match", "assets.match_asset"),
("match", "assets.view_asset"),
("platform", "assets.view_platform"),
("gateways", "assets.view_gateway"),
("accounts", "assets.view_account"),
@@ -181,33 +180,18 @@ class AssetViewSet(SuggestionMixin, BaseAssetViewSet):
def sync_platform_protocols(self, request, *args, **kwargs):
platform_id = request.data.get('platform_id')
platform = get_object_or_404(Platform, pk=platform_id)
assets = platform.assets.all()
asset_ids = list(platform.assets.values_list('id', flat=True))
platform_protocols = list(platform.protocols.values('name', 'port'))
platform_protocols = {
p['name']: p['port']
for p in platform.protocols.values('name', 'port')
}
asset_protocols_map = defaultdict(set)
protocols = assets.prefetch_related('protocols').values_list(
'id', 'protocols__name'
)
for asset_id, protocol in protocols:
asset_id = str(asset_id)
asset_protocols_map[asset_id].add(protocol)
objs = []
for asset_id, protocols in asset_protocols_map.items():
protocol_names = set(platform_protocols) - protocols
if not protocol_names:
continue
for name in protocol_names:
objs.append(
Protocol(
name=name,
port=platform_protocols[name],
asset_id=asset_id,
)
)
Protocol.objects.bulk_create(objs)
with transaction.atomic():
if asset_ids:
Protocol.objects.filter(asset_id__in=asset_ids).delete()
if asset_ids and platform_protocols:
objs = []
for aid in asset_ids:
for p in platform_protocols:
objs.append(Protocol(name=p['name'], port=p['port'], asset_id=aid))
Protocol.objects.bulk_create(objs)
return Response(status=status.HTTP_200_OK)
def filter_bulk_update_data(self):

View File

@@ -14,6 +14,7 @@ class FavoriteAssetViewSet(BulkModelViewSet):
serializer_class = FavoriteAssetSerializer
permission_classes = (IsValidUser,)
filterset_fields = ['asset']
page_no_limit = True
def dispatch(self, request, *args, **kwargs):
with tmp_to_root_org():

View File

@@ -43,7 +43,7 @@ class NodeViewSet(SuggestionMixin, OrgBulkModelViewSet):
search_fields = ('full_value',)
serializer_class = serializers.NodeSerializer
rbac_perms = {
'match': 'assets.match_node',
'match': 'assets.view_node',
'check_assets_amount_task': 'assets.change_node'
}

View File

@@ -7,15 +7,18 @@ from rest_framework.decorators import action
from rest_framework.response import Response
from assets.const import AllTypes
from assets.models import Platform, Node, Asset, PlatformProtocol
from assets.models import Platform, Node, Asset, PlatformProtocol, PlatformAutomation
from assets.serializers import PlatformSerializer, PlatformProtocolSerializer, PlatformListSerializer
from common.api import JMSModelViewSet
from common.permissions import IsValidUser
from common.serializers import GroupedChoiceSerializer
from rbac.models import RoleBinding
__all__ = ['AssetPlatformViewSet', 'PlatformAutomationMethodsApi', 'PlatformProtocolViewSet']
class PlatformFilter(filters.FilterSet):
name__startswith = filters.CharFilter(field_name='name', lookup_expr='istartswith')
@@ -40,6 +43,7 @@ class AssetPlatformViewSet(JMSModelViewSet):
'ops_methods': 'assets.view_platform',
'filter_nodes_assets': 'assets.view_platform',
}
page_no_limit = True
def get_queryset(self):
# 因为没有走分页逻辑,所以需要这里 prefetch
@@ -63,6 +67,13 @@ class AssetPlatformViewSet(JMSModelViewSet):
return super().get_object()
return self.get_queryset().get(name=pk)
def check_permissions(self, request):
if self.action == 'list' and RoleBinding.is_org_admin(request.user):
return True
else:
return super().check_permissions(request)
def check_object_permissions(self, request, obj):
if request.method.lower() in ['delete', 'put', 'patch'] and obj.internal:
self.permission_denied(
@@ -101,7 +112,10 @@ class PlatformProtocolViewSet(JMSModelViewSet):
class PlatformAutomationMethodsApi(generics.ListAPIView):
permission_classes = (IsValidUser,)
queryset = PlatformAutomation.objects.none()
rbac_perms = {
'list': 'assets.view_platform'
}
@staticmethod
def automation_methods():

View File

@@ -13,3 +13,13 @@ class ProtocolListApi(ListAPIView):
def get_queryset(self):
return list(Protocol.protocols())
def filter_queryset(self, queryset):
search = self.request.query_params.get("search", "").lower().strip()
if not search:
return queryset
queryset = [
p for p in queryset
if search in p['label'].lower() or search in p['value'].lower()
]
return queryset

View File

@@ -161,6 +161,7 @@ class CategoryTreeApi(SerializeToTreeNodeMixin, generics.ListAPIView):
'GET': 'assets.view_asset',
'list': 'assets.view_asset',
}
queryset = Node.objects.none()
def get_assets(self):
key = self.request.query_params.get('key')

View File

@@ -11,15 +11,20 @@ class FormatAssetInfo:
@staticmethod
def get_cpu_model_count(cpus):
try:
models = [cpus[i + 1] + " " + cpus[i + 2] for i in range(0, len(cpus), 3)]
if len(cpus) % 3 == 0:
step = 3
models = [cpus[i + 2] for i in range(0, len(cpus), step)]
elif len(cpus) % 2 == 0:
step = 2
models = [cpus[i + 1] for i in range(0, len(cpus), step)]
else:
raise ValueError("CPU list format not recognized")
model_counts = Counter(models)
result = ', '.join([f"{model} x{count}" for model, count in model_counts.items()])
except Exception as e:
print(f"Error processing CPU model list: {e}")
result = ''
return result
@staticmethod

View File

@@ -4,6 +4,7 @@
ansible_shell_type: sh
ansible_connection: local
ansible_python_interpreter: "{{ local_python_interpreter }}"
ansible_timeout: 30
tasks:
- name: Test asset connection (pyfreerdp)

View File

@@ -4,7 +4,7 @@
ansible_connection: local
ansible_shell_type: sh
ansible_become: false
ansible_timeout: 30
tasks:
- name: Test asset connection (paramiko)
ssh_ping:

View File

@@ -3,7 +3,7 @@
vars:
ansible_connection: local
ansible_shell_type: sh
ansible_timeout: 30
tasks:
- name: Test asset connection (telnet)
telnet_ping:

View File

@@ -2,6 +2,7 @@
gather_facts: no
vars:
ansible_python_interpreter: "{{ local_python_interpreter }}"
ansible_timeout: 30
tasks:
- name: Test MongoDB connection
@@ -16,3 +17,5 @@
ssl_certfile: "{{ jms_asset.secret_info.client_key | default('') }}"
connection_options:
- tlsAllowInvalidHostnames: "{{ jms_asset.spec_info.allow_invalid_cert}}"
register: result
failed_when: not result.is_available

View File

@@ -6,6 +6,7 @@
ca_cert: "{{ jms_asset.secret_info.ca_cert | default('') }}"
ssl_cert: "{{ jms_asset.secret_info.client_cert | default('') }}"
ssl_key: "{{ jms_asset.secret_info.client_key | default('') }}"
ansible_timeout: 30
tasks:
- name: Test MySQL connection

View File

@@ -2,6 +2,7 @@
gather_facts: no
vars:
ansible_python_interpreter: "{{ local_python_interpreter }}"
ansible_timeout: 30
tasks:
- name: Test Oracle connection

View File

@@ -6,7 +6,7 @@
ca_cert: "{{ jms_asset.secret_info.ca_cert | default('') }}"
ssl_cert: "{{ jms_asset.secret_info.client_cert | default('') }}"
ssl_key: "{{ jms_asset.secret_info.client_key | default('') }}"
ansible_timeout: 30
tasks:
- name: Test PostgreSQL connection
community.postgresql.postgresql_ping:

View File

@@ -2,14 +2,17 @@
gather_facts: no
vars:
ansible_python_interpreter: "{{ local_python_interpreter }}"
ansible_timeout: 30
tasks:
- name: Test SQLServer connection
community.general.mssql_script:
mssql_script:
login_user: "{{ jms_account.username }}"
login_password: "{{ jms_account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
name: '{{ jms_asset.spec_info.db_name }}'
encryption: "{{ jms_asset.encryption | default(None) }}"
tds_version: "{{ jms_asset.tds_version | default(None) }}"
script: |
SELECT @@version

View File

@@ -14,6 +14,10 @@ class Connectivity(TextChoices):
NTLM_ERR = 'ntlm_err', _('NTLM credentials rejected error')
CREATE_TEMPORARY_ERR = 'create_temp_err', _('Create temporary error')
@classmethod
def as_dict(cls):
return {choice.value: choice.label for choice in cls}
class AutomationTypes(TextChoices):
ping = 'ping', _('Ping')

View File

@@ -20,3 +20,7 @@ class Category(ChoicesMixin, models.TextChoices):
_category = getattr(cls, category.upper(), None)
choices = [(_category.value, _category.label)] if _category else cls.choices
return choices
@classmethod
def as_dict(cls):
return {choice.value: choice.label for choice in cls}

View File

@@ -1,5 +1,6 @@
from django.utils.translation import gettext_lazy as _
from orgs.models import Organization
from .base import BaseType
@@ -52,3 +53,41 @@ class GPTTypes(BaseType):
return [
cls.CHATGPT,
]
CHATX_NAME = 'ChatX'
def create_or_update_chatx_resources(chatx_name=CHATX_NAME, org_id=Organization.SYSTEM_ID):
from django.apps import apps
platform_model = apps.get_model('assets', 'Platform')
asset_model = apps.get_model('assets', 'Asset')
account_model = apps.get_model('accounts', 'Account')
platform, __ = platform_model.objects.get_or_create(
name=chatx_name,
defaults={
'internal': True,
'type': chatx_name,
'category': 'ai',
}
)
asset, __ = asset_model.objects.get_or_create(
address=chatx_name,
defaults={
'name': chatx_name,
'platform': platform,
'org_id': org_id
}
)
account, __ = account_model.objects.get_or_create(
username=chatx_name,
defaults={
'name': chatx_name,
'asset': asset,
'org_id': org_id
}
)
return asset, account

View File

@@ -250,6 +250,12 @@ class Protocol(ChoicesMixin, models.TextChoices):
'default': False,
'label': _('Auth username')
},
'enable_cluster_mode': {
'type': 'bool',
'default': False,
'label': _('Enable cluster mode'),
'help_text': _('Enable if this Redis instance is part of a cluster')
},
}
},
}
@@ -262,6 +268,14 @@ class Protocol(ChoicesMixin, models.TextChoices):
'port_from_addr': True,
'required': True,
'secret_types': ['token'],
'setting': {
'namespace': {
'type': 'str',
'required': False,
'default': '',
'label': _('Namespace')
}
}
},
cls.http: {
'port': 80,
@@ -349,7 +363,7 @@ class Protocol(ChoicesMixin, models.TextChoices):
for protocol, config in cls.settings().items():
if not xpack_enabled and config.get('xpack', False):
continue
protocols.append(protocol)
protocols.append({'label': protocol.label, 'value': protocol.value})
from assets.models.platform import PlatformProtocol
custom_protocols = (

View File

@@ -0,0 +1,25 @@
# Generated by Django 4.1.13 on 2025-12-13 02:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('assets', '0019_alter_asset_connectivity'),
]
operations = [
migrations.CreateModel(
name='AssetNodeBackup',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('asset_id', models.CharField(max_length=1024, verbose_name='Asset ID')),
('node_id', models.CharField(max_length=1024, verbose_name='Node ID')),
],
options={
'verbose_name': 'Asset Node Backup',
'db_table': 'assets_asset_nodes_backup',
},
),
]

View File

@@ -0,0 +1,343 @@
# Generated by Django 4.1.13 on 2025-12-12 03:55
"""
【数据迁移流程】
本迁移将 Asset.nodes 从自动生成的 M2M through 表迁移到自定义的 AssetNode 模型,并添加 node_key 字段。
五阶段迁移流程:
【阶段1】读取 through 表并备份到 AssetNodeBackup 中
- 创建 AssetNodeBackup 表用于备份
- 读取原 Asset.nodes.through 表中所有 (asset_id, node_id) 数据
- 将数据保存到全局变量 through_old_data 中(内存缓存)
- 同时将数据备份到 AssetNodeBackup 表中(持久化,支持重试)
- 好处:即使迁移中断,再次执行时也可以从 backup 恢复
【阶段2】数据库表结构修改
- 删除 Asset.nodes 的 M2M 关系字段
- 创建新的 AssetNode 自定义 through 模型
- 重新添加 Asset.nodes M2M 字段,指向新的 AssetNode
- 创建优化后的索引和修改一个联合唯一索引:
* idx_node_key_asset_id: 支持按 node_key 范围查询资产
* idx_node_id_asset_id: 支持按 node_id 查询资产
* idx_asset_id_node_id_key: 支持按 asset_id 反向查询节点
* unique_together (asset, node): 保证每个资产和节点组合唯一
【阶段3】恢复数据并填充 node_key
- 优先使用内存缓存中的数据through_old_data
- 如果内存为空,说明之前可能迁移失败过,则从 AssetNodeBackup 表加载数据
- 预加载 Node.key 映射,为每条数据填充 node_key 字段
- 预加载已存在的 (asset_id, node_id) 对,避免重复插入
- 批量插入到 AssetNode 表中50k/batch
- 如果批插入失败,降级为单条插入
- 统计插入和跳过的记录数
【阶段4】清理 through 表中的重复数据
- 找出原 through 表中 node_key 为空的数据(这些是重复或无效的)
- 显示前 100 条要删除的数据的 (asset_id, node_id)
- 分批删除50k/batch
- 输出删除的总数
【阶段5】删除备份表 (或用户手动删除也可以)
- 验证 AssetNodeBackup 表中的数据(显示记录数)
- 清空备份表中的所有数据
- 删除 AssetNodeBackup 表
- 意义:迁移完成后,备份表已无用,清理数据库空间
【数据一致性保证】
- 备份表AssetNodeBackup 在阶段1中持久化所有原始数据支持恢复
- 去重阶段3 中使用 set 预检测避免重复
- 容错阶段3 批插入失败时自动降级到单条插入
- 清理阶段4 只删除 node_key 为空的无效数据
- 清理阶段5 删除已完成使命的备份表
【字段映射】
AssetNode.node_key 来自 Node.key
"""
import time
from datetime import datetime
from django.db import migrations, models, transaction
from django.db.models import Count, Q
import django.db.models.deletion
import assets.models.asset.common
# ============== 全局变量 ==============
through_old_data = []
migration_stats = {'backed_up': 0, 'restored': 0}
def log(msg):
print(f"[{datetime.now().strftime('%H:%M:%S')}] {msg}")
def load_data_from_backup(AssetNodeBackup):
"""从 backup 表加载数据到内存"""
global through_old_data
total = AssetNodeBackup.objects.count()
if total == 0:
log("⚠ backup 表为空,无数据可恢复")
return False
log(f"从 backup 表加载 {total:,} 条数据...")
batch_size = 50000
start = time.time()
for offset in range(0, total, batch_size):
batch = list(AssetNodeBackup.objects.all().values_list('asset_id', 'node_id')[offset:offset + batch_size])
through_old_data.extend(batch)
log(f" 已加载 {len(through_old_data):,}/{total:,}")
log(f"✓ 从 backup 加载完成! 耗时 {time.time()-start:.1f}s")
return True
def phase1_save_and_backup(apps, schema_editor):
"""阶段1: 读取 through 所有数据,加载到全局变量,并保存到 backup 中"""
global through_old_data, migration_stats
Asset = apps.get_model('assets', 'Asset')
AssetNodeBackup = apps.get_model('assets', 'AssetNodeBackup')
asset_node_through = Asset.nodes.through
total = asset_node_through.objects.count()
log(f"\n{'='*50}")
log("【阶段1】读取 through 数据并备份")
log(f"{'='*50}")
log(f"从 through 表读取 {total:,} 条数据...")
batch_size = 50000
start = time.time()
backup_batch = []
# 阶段1-1: 读取所有数据到内存
for offset in range(0, total, batch_size):
batch = list(asset_node_through.objects.all().values_list('asset_id', 'node_id')[offset:offset + batch_size])
through_old_data.extend(batch)
# 准备备份数据
backup_objs = [AssetNodeBackup(asset_id=aid, node_id=nid) for aid, nid in batch]
backup_batch.extend(backup_objs)
log(f" 已读取 {len(through_old_data):,}/{total:,} ({len(through_old_data)/total*100:.1f}%)")
# 阶段1-2: 写入备份到数据库并立即提交
log(f"\n写入 {len(backup_batch):,} 条备份数据到数据库...")
backup_start = time.time()
backup_batch_size = 50000
for i in range(0, len(backup_batch), backup_batch_size):
batch = backup_batch[i:i + backup_batch_size]
with transaction.atomic():
created = AssetNodeBackup.objects.bulk_create(batch, batch_size=backup_batch_size, ignore_conflicts=True)
migration_stats['backed_up'] += len(created)
log(f" 已备份 {min(i+backup_batch_size, len(backup_batch)):,}/{len(backup_batch):,}")
log(f"✓ 阶段1完成! 读取耗时 {time.time()-start:.1f}s, 备份耗时 {time.time()-backup_start:.1f}s")
log(f" 内存缓存: {len(through_old_data):,}")
log(f" 数据库备份: {migration_stats['backed_up']:,}\n")
def phase3_restore_data_and_set_node_key(apps, schema_editor):
"""阶段3: 恢复数据时先查看全局变量是否有如果没有从backup中加载"""
global through_old_data, migration_stats
Node = apps.get_model('assets', 'Node')
AssetNode = apps.get_model('assets', 'AssetNode')
AssetNodeBackup = apps.get_model('assets', 'AssetNodeBackup')
log(f"\n{'='*50}")
log("【阶段3】恢复数据并设置 node_key")
log(f"{'='*50}")
# 检查内存是否有数据,如果没有则从 backup 加载
if not through_old_data:
log("内存缓存为空,从 backup 表加载数据...")
if not load_data_from_backup(AssetNodeBackup):
log("✗ 无法恢复数据backup 表也为空")
return
log()
else:
log(f"使用内存缓存的 {len(through_old_data):,} 条数据\n")
total = len(through_old_data)
log(f"开始恢复 {total:,} 条数据到 AssetNode 表...")
# 预加载 node_key 映射
id_key_map = {str(item['id']): item['key'] for item in Node.objects.values('id', 'key')}
# 预加载已存在的数据,避免重复
existing = set(AssetNode.objects.values_list('asset_id', 'node_id'))
log(f"数据库中已存在 {len(existing):,} 条记录\n")
batch_size = 50000
start = time.time()
skipped = 0
for i in range(0, total, batch_size):
batch = through_old_data[i:i + batch_size]
# 去重:只保留不存在的记录
objs = []
for aid, nid in batch:
if (aid, nid) not in existing:
objs.append(AssetNode(asset_id=aid, node_id=nid, node_key=id_key_map.get(str(nid), '')))
existing.add((aid, nid))
else:
skipped += 1
# 批量插入
if objs:
try:
AssetNode.objects.bulk_create(objs, batch_size=batch_size, ignore_conflicts=True)
migration_stats['restored'] += len(objs)
except Exception as e:
log(f" ✗ 批插入失败: {str(e)}")
# 降级:逐条插入
for obj in objs:
try:
obj.save()
migration_stats['restored'] += 1
except Exception as save_err:
log(f" ✗ 跳过 asset_id={obj.asset_id}, node_id={obj.node_id}: {str(save_err)}")
skipped += 1
progress = min(i + batch_size, total)
log(f" 已恢复 {progress:,}/{total:,} (插入{migration_stats['restored']:,} 跳过{skipped:,})")
log(f"✓ 阶段3完成! 耗时 {time.time()-start:.1f}s")
log(f" 插入: {migration_stats['restored']:,}")
log(f" 跳过: {skipped:,}\n")
def phase4_cleanup_duplicates(apps, schema_editor):
"""阶段4: 删除 through 表中 node_key 为空的数据"""
Asset = apps.get_model('assets', 'Asset')
asset_node_through = Asset.nodes.through
log(f"\n{'='*50}")
log("【阶段4】清理 through 表中 node_key 为空的数据")
log(f"{'='*50}")
# 找出 node_key 为空的记录
empty_node_key = asset_node_through.objects.filter(Q(node_key='') | Q(node_key__isnull=True))
total = empty_node_key.count()
if total == 0:
log("✓ 没有 node_key 为空的数据,无需清理\n")
return
log(f"发现 {total:,} 条 node_key 为空的数据")
start = time.time()
batch_size = 50000
deleted = 0
# 获取要删除的数据信息
to_delete_records = list(
empty_node_key.values_list('asset_id', 'node_id', 'id')
)
log("删除详情:")
for aid, nid, record_id in to_delete_records[:100]: # 显示前100条
log(f" asset_id={aid}, node_id={nid}")
if len(to_delete_records) > 100:
log(f" ... 还有 {len(to_delete_records)-100:,}")
# 分批删除
for offset in range(0, len(to_delete_records), batch_size):
batch_ids = [record_id for _, _, record_id in to_delete_records[offset:offset + batch_size]]
if batch_ids:
delete_count, _ = asset_node_through.objects.filter(id__in=batch_ids).delete()
deleted += delete_count
log(f" 已删除 {deleted:,}/{total:,}")
log(f"✓ 阶段4完成! 耗时 {time.time()-start:.1f}s")
log(f" 删除: {deleted:,} 条 node_key 为空的数据\n")
def phase5_cleanup_backup_table(apps, schema_editor):
"""阶段5: 删除备份表"""
log(f"\n{'='*50}")
log("【阶段5】删除 AssetNodeBackup 备份表")
log(f"{'='*50}")
AssetNodeBackup = apps.get_model('assets', 'AssetNodeBackup')
total = AssetNodeBackup.objects.count()
log(f"备份表中有 {total:,} 条数据")
start = time.time()
# 删除所有备份数据
delete_count, _ = AssetNodeBackup.objects.all().delete()
log(f"✓ 删除 {delete_count:,} 条备份数据")
log(f"✓ 阶段5完成! 耗时 {time.time()-start:.1f}s\n")
class Migration(migrations.Migration):
dependencies = [
('assets', '0020_assetnodebackup'),
]
operations = [
# 阶段1保存和备份
migrations.RunPython(phase1_save_and_backup),
# 阶段2数据库表结构操作
migrations.RemoveField(
model_name='asset',
name='nodes',
),
migrations.CreateModel(
name='AssetNode',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('node_key', models.CharField(db_index=True, default='', max_length=64, verbose_name='Node key')),
('asset', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='assets.asset', verbose_name='Asset')),
('node', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='assets.node', verbose_name='Node')),
],
options={
'verbose_name': 'Asset Node',
'db_table': 'assets_asset_nodes',
},
),
migrations.AddField(
model_name='asset',
name='nodes',
field=models.ManyToManyField(default=assets.models.asset.common.default_node, related_name='assets', through='assets.AssetNode', to='assets.node', verbose_name='Nodes'),
),
migrations.AlterUniqueTogether(
name='assetnode',
unique_together={('asset', 'node_key'), ('asset', 'node')},
),
migrations.AddIndex(
model_name='assetnode',
index=models.Index(fields=['node_key', 'asset_id'], name='idx_node_key_asset_id'),
),
migrations.AddIndex(
model_name='assetnode',
index=models.Index(fields=['node_id', 'asset_id'], name='idx_node_id_asset_id'),
),
migrations.AddIndex(
model_name='assetnode',
index=models.Index(fields=['asset_id', 'node_id', 'node_key'], name='idx_asset_id_node_id_key'),
),
# 阶段3恢复数据
migrations.RunPython(phase3_restore_data_and_set_node_key),
# 阶段4清理重复数据
migrations.RunPython(phase4_cleanup_duplicates),
# 阶段5删除备份表 (或用户手动删除也可以)
# migrations.RunPython(phase5_cleanup_backup_table),
# migrations.DeleteModel(
# name='AssetNodeBackup',
# ),
]

View File

@@ -9,3 +9,4 @@ from .node import *
from .favorite_asset import *
from .automations import *
from .my_asset import *
from .asset_node import *

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