Compare commits
1160 Commits
version-te
...
web/testin
Author | SHA1 | Date | |
---|---|---|---|
f0256a0535 | |||
142a985914 | |||
a8531d498a | |||
f8cb4e880b | |||
3ced637db3 | |||
409934196c | |||
62c882cb0e | |||
033b55ba51 | |||
e5e14d3b5a | |||
9475c1b0cf | |||
6875efcfdd | |||
5cf4172a6f | |||
dbfa5f2fd1 | |||
e44341d5e0 | |||
f77ee77f7e | |||
d4b39b30cb | |||
b0507d2063 | |||
d0a459076b | |||
e20eaac56e | |||
085ab3c2dd | |||
c0063c1749 | |||
ee58cf0c1c | |||
1f2654f25f | |||
1dec9bde3c | |||
259537ee34 | |||
303ba13791 | |||
7a74baaf8e | |||
e0a2bd2cd5 | |||
7d3dda171d | |||
ad2c2eecb8 | |||
df3de9218c | |||
6f8460c4fe | |||
68172c388f | |||
d4f0aba430 | |||
ef78ee3440 | |||
1cf4ccdde5 | |||
11d41a2ee4 | |||
8db1d86c6b | |||
8f7fe8e744 | |||
e0dbd8c53f | |||
ba38fb6ff6 | |||
639f7d53c1 | |||
de9d8a40f6 | |||
9e32c78c8c | |||
91cb2ef883 | |||
ad5e447b3d | |||
d5ce530179 | |||
f6a9773930 | |||
7721d4d0c2 | |||
a5e45ba78e | |||
96f04d32ea | |||
d7bac37ba8 | |||
c3509382de | |||
c09d36a1f7 | |||
db2b5f035f | |||
2a74225775 | |||
b8188708dc | |||
2a5a76e369 | |||
4d3ec68494 | |||
b8560f2a86 | |||
f312250dc9 | |||
aef8b49f6b | |||
2ae08aa1c6 | |||
a8488ee35a | |||
a3e015f835 | |||
0f36defbb9 | |||
8de811a56f | |||
7328b8e3a6 | |||
6312a20bcc | |||
631537851e | |||
b93759f318 | |||
9ca3ff9e49 | |||
6aefe2d143 | |||
5c8a9abb33 | |||
d6e7cb2cff | |||
50d66eda9e | |||
de37748f17 | |||
c579b5c36c | |||
07040bb344 | |||
59ffcdd34d | |||
d30b87a2bb | |||
f3d5e659eb | |||
95463dd76a | |||
c702b0fd07 | |||
3d6e1f9d33 | |||
bfc2fe7703 | |||
14e8d1d0f4 | |||
5103eebfad | |||
210befd1ea | |||
37fe20e576 | |||
26732389a1 | |||
0fe751269e | |||
a824fda339 | |||
d8fefb1c7b | |||
f4d8191dec | |||
3338a79ef0 | |||
9c9581a3de | |||
fbad6fb2a4 | |||
24e74e0263 | |||
763a19b914 | |||
b8006068e9 | |||
16c7155268 | |||
ef2fb6d5fc | |||
bac0237ce0 | |||
038170314d | |||
d198176ff9 | |||
186d023c94 | |||
cc85806b39 | |||
c345a77c1a | |||
11d0acf9dd | |||
2fc0c6e0ad | |||
6f31c802c2 | |||
2de2189985 | |||
e4c8e30814 | |||
8bd514e17d | |||
d758e6065b | |||
42e0ff6492 | |||
1789ed67e1 | |||
56d02e94f1 | |||
7b64620615 | |||
fc39323ea0 | |||
00427b20e8 | |||
18e3e7c875 | |||
c7d8bbace0 | |||
07ad795972 | |||
77a83d75b7 | |||
c846c8089a | |||
453f7b8641 | |||
cb7b44e751 | |||
e9c79df56b | |||
82bf113b5e | |||
e5c41fc928 | |||
d30defc6fa | |||
c76313a5aa | |||
31b62f6b3b | |||
7e78fe5802 | |||
bde509a5b9 | |||
0510200d8c | |||
6c96bc7dfe | |||
29f3e2789d | |||
f4ef8f5739 | |||
b94db1d10d | |||
dc93a941fb | |||
e6012fe2d4 | |||
90fb64006d | |||
b50cdd674f | |||
24910d1b4d | |||
8f26708bde | |||
dca3391554 | |||
7392065e35 | |||
52388dadf5 | |||
c517d4690a | |||
136b7dea54 | |||
cb178f7f2d | |||
2d565f1943 | |||
98c8402f11 | |||
8915904cc7 | |||
ca960f3286 | |||
7c5314eb66 | |||
97a8d8ba60 | |||
4f06ecbee6 | |||
1b19b3dd11 | |||
9458c486c5 | |||
1fe0f474bd | |||
326b89fe88 | |||
755851d774 | |||
17a58a1095 | |||
361765cd8d | |||
8adbba606c | |||
cb4bc5bd87 | |||
861992f576 | |||
f827c269da | |||
80072f3781 | |||
e0ac3dedf4 | |||
f220060ea2 | |||
7c22e9cfa9 | |||
e7241927e5 | |||
059f81735e | |||
eff85e489c | |||
0caa8cf0fa | |||
778bd9ba63 | |||
632f098a34 | |||
40b15ded2a | |||
17acc9457d | |||
843431cfed | |||
7cadcbfa06 | |||
2996f20b74 | |||
d575eb8dcc | |||
dd86a90225 | |||
db5168480c | |||
3b1034b9a2 | |||
3086d15f08 | |||
a1153d3393 | |||
f40feaf95f | |||
ba87fd8714 | |||
ccebe355aa | |||
94de772a3d | |||
5f4e49f586 | |||
6bd1b9fa32 | |||
22215bc887 | |||
9b618ca54b | |||
cc18f352aa | |||
49fe670932 | |||
422eb0890c | |||
8626d7a7aa | |||
53a44435f8 | |||
f1d173f94e | |||
e25ceb5041 | |||
72a6f369ef | |||
ef16328005 | |||
89fafbd6ad | |||
d8a855e16d | |||
f9cd3b9b34 | |||
909c227894 | |||
0690dffa58 | |||
48ff62d502 | |||
988131fb57 | |||
19e0a282c6 | |||
234f06a362 | |||
b3340507a2 | |||
94482daa97 | |||
942019d31f | |||
54743e8187 | |||
833d20349e | |||
1b2816eb14 | |||
e6fd7cc1fc | |||
0bbbc7def2 | |||
43fd3eecda | |||
631b120e4f | |||
c7c7e28cef | |||
9ea517d606 | |||
5201a37214 | |||
a448107feb | |||
7b7a7e3073 | |||
1eb103994d | |||
ae97eac780 | |||
3c7abaef01 | |||
2def291773 | |||
7f17c5f212 | |||
2bd7b80579 | |||
340c3241e6 | |||
ca3cdc3fd2 | |||
c23ee42d9a | |||
0cc853e272 | |||
6e12277903 | |||
2c781ae423 | |||
81540fdae5 | |||
22a6acf56c | |||
29c0d1d5f4 | |||
2b17947b64 | |||
2f42144b33 | |||
eef02f2892 | |||
7c3eb96525 | |||
ff06214b0e | |||
bdde6775bc | |||
57399c2907 | |||
4df1b50542 | |||
c5e0e5e09d | |||
8d7305caec | |||
9448d06301 | |||
e8a1929993 | |||
9edece404c | |||
a636df2863 | |||
5ee24bd28b | |||
8e7ae07f13 | |||
40c1934ed9 | |||
d7e9c86672 | |||
016299dd41 | |||
b6157ecaf1 | |||
49e7c5b873 | |||
6a79b3a4af | |||
35cd126406 | |||
f89a4fc276 | |||
ea76295976 | |||
4d7f380b2d | |||
6e98c9a6a9 | |||
cb8379031a | |||
45bc16286c | |||
c0521762bc | |||
0c604ceba4 | |||
30e39c75ff | |||
6d7bebbcc3 | |||
dc332ec7b0 | |||
31e94a2814 | |||
eb08214f0e | |||
a5ab8a618e | |||
b8cbdcae22 | |||
ae86184511 | |||
b704388c2f | |||
a35f9fdd7b | |||
d95220be0e | |||
ba1b86efa1 | |||
cd93de1141 | |||
cc148bd552 | |||
8f82dac84e | |||
89c08f2588 | |||
113d6cc45f | |||
05cfbca5f2 | |||
385f9bcbac | |||
86bc5b4cdb | |||
8d5d9f35ef | |||
439169d5e7 | |||
e405b33f9f | |||
a9c13d4d10 | |||
12b16b17a2 | |||
3473abee32 | |||
b5a0b3a521 | |||
837a0325ca | |||
b1050e8825 | |||
7bb90b1661 | |||
8f755785ea | |||
adc0ec8ee4 | |||
9379b3d178 | |||
18eef8ae05 | |||
f0e22fd08b | |||
ce5297a6cd | |||
74c8df8782 | |||
2d897fac48 | |||
2eb47c9efa | |||
9852041f38 | |||
7f74936212 | |||
4f40b1e27c | |||
041e407153 | |||
31b891428e | |||
4ab8247847 | |||
af24edf8c1 | |||
f8bfd12e31 | |||
993fc4b77b | |||
3ee2be09bf | |||
b3e3948f44 | |||
117a5cd88d | |||
342a40212e | |||
15ae11d9d5 | |||
e11df56f21 | |||
3771af5282 | |||
0718053c56 | |||
3e5014bfea | |||
78f49ddc04 | |||
744bc54231 | |||
44ba30ad75 | |||
63b991f137 | |||
7f9acb8a2b | |||
ce3ba32044 | |||
25e6a69331 | |||
78d07cc355 | |||
3c4df47fe3 | |||
8ed1805cb8 | |||
4d23db73ca | |||
72783953fb | |||
3b0fdb3dbd | |||
23161eed12 | |||
8918427588 | |||
5d858020f6 | |||
198e8b98a8 | |||
88e9c9b669 | |||
0c652a210d | |||
105a90d2e7 | |||
68f5abe318 | |||
59d4c18636 | |||
b67e2a1144 | |||
fc025651ce | |||
7cedc840b0 | |||
5ba731e48b | |||
c792534a50 | |||
a136fd8b54 | |||
fb63c1f3e9 | |||
0b15ab3f27 | |||
f9fd67c2b8 | |||
4ac19f9d44 | |||
74d3e92bac | |||
207fa13405 | |||
208e4a8bed | |||
ee245ab390 | |||
60c8837082 | |||
6cf418a37e | |||
254761e930 | |||
d85f8758fe | |||
84bfb37b60 | |||
578ff13868 | |||
d12acb5bcd | |||
0e8b9a6409 | |||
6171443e61 | |||
5fedd616d9 | |||
5dd6498694 | |||
cf5102ed20 | |||
d3b2032c33 | |||
1e5df1c405 | |||
96eabe269c | |||
3e869a0ec7 | |||
7276a416f6 | |||
a989390533 | |||
562c52a48b | |||
c3cb9bc778 | |||
5f65a7c6cc | |||
95d26563e7 | |||
1cac1492d7 | |||
6c1ac48bd9 | |||
97f11f7aa8 | |||
6db763f7dc | |||
16b5f692ee | |||
80c1bd690c | |||
040dcaa9d6 | |||
66a16752e4 | |||
70c0e1be99 | |||
5beea4624f | |||
50fffa72cc | |||
dae4bf0d6b | |||
823851652e | |||
ae7f7c9930 | |||
5ce4ed4dd3 | |||
5582cc7745 | |||
c384ed5f52 | |||
02e2ba8971 | |||
925d5c80df | |||
1de69a7bd6 | |||
c6979a48e0 | |||
6e73d60305 | |||
f388cac07c | |||
cf593e5cb9 | |||
c3a98e5d5f | |||
1048729599 | |||
72442b37e5 | |||
211cdb3a21 | |||
4cca16750e | |||
b2d261dd1c | |||
0663100429 | |||
66c3261eeb | |||
bf7570bc36 | |||
20b52d0dbd | |||
a1f5e284c4 | |||
0e4737d38f | |||
609b10f7f8 | |||
2cff3d15e7 | |||
4f1d49417c | |||
0766a47b4f | |||
bd1ddfebd6 | |||
a841743c74 | |||
0974456ac8 | |||
d44d5a44a1 | |||
edf5c8686a | |||
70ace8b209 | |||
c3509e63af | |||
89b8206176 | |||
908d87c142 | |||
4ab4e81fb0 | |||
6dae1a4fe7 | |||
d11de73e95 | |||
b08fb5fdf1 | |||
3c9e8c7287 | |||
691d0be41e | |||
dfbaccbab6 | |||
f3bdb189f6 | |||
85b3523639 | |||
9ff61a7120 | |||
f742b986a7 | |||
177bdfa689 | |||
c3445374c2 | |||
c2da6822dc | |||
493294ef9f | |||
17f807e8b0 | |||
96eb98500c | |||
ddd75f6d09 | |||
fbad02fac1 | |||
fbab822db1 | |||
d8316eea9b | |||
8182c9f7c2 | |||
5d94b97e97 | |||
35ddbb6d75 | |||
2b8bc38fc3 | |||
9b0b504531 | |||
c312430007 | |||
4e65c205e3 | |||
372a66c876 | |||
3630349388 | |||
347746cbcd | |||
ef2e1ad27b | |||
8a6b34eb5c | |||
26f72bcac4 | |||
f04466b3be | |||
4ba53d2f08 | |||
7a13046a27 | |||
939e2c1edd | |||
cf06b4177a | |||
f8079d63fa | |||
576a56c562 | |||
cf9b14213e | |||
73cbdb77ed | |||
fd66be9fa2 | |||
96bf9ee898 | |||
6c4c535d57 | |||
0ed4bba5a5 | |||
6e31e5b889 | |||
a5467c6e19 | |||
09832355e3 | |||
6ffef878f0 | |||
644090dc58 | |||
d07508b9a4 | |||
44d7e81a93 | |||
2e91b9d035 | |||
964c6a1050 | |||
90a1c5ab85 | |||
8162c1ec86 | |||
ab46610d9b | |||
6909b58279 | |||
6d7a06227f | |||
1459a13991 | |||
1921ce39f6 | |||
263cff6393 | |||
5a61688472 | |||
919b56c466 | |||
db7bc8b7ad | |||
5768cb5858 | |||
5b77bc33c7 | |||
93650e925a | |||
83823068fe | |||
d922f41438 | |||
ef3d545d7a | |||
e9efbb2161 | |||
a3634ab21d | |||
f28209548b | |||
9589e04072 | |||
6490703ba3 | |||
ca2fce05f5 | |||
9dc813d9ab | |||
833c66a9dd | |||
5d54f696d4 | |||
0746652995 | |||
a1a55c644a | |||
fce57d258e | |||
17e30b7adc | |||
c5b3f8a578 | |||
3a3619fa18 | |||
21b933efff | |||
97fc2cba69 | |||
7ef627d476 | |||
d16c603499 | |||
99a69bb52f | |||
ac8192d660 | |||
cdf3449230 | |||
ef2a40ed7d | |||
09cacbd76b | |||
cb33f0d1e2 | |||
90af4b29a6 | |||
6b9158591e | |||
9c15cda191 | |||
046b8d5cbf | |||
8b74b83983 | |||
8de038b387 | |||
2edc651582 | |||
85594a119c | |||
1a97ccea03 | |||
99ad492951 | |||
ff4ec6f9b4 | |||
0c49de67b8 | |||
0d73528ec7 | |||
80ca4e5722 | |||
1ebe200a46 | |||
5683c81f27 | |||
f0477309d5 | |||
04d613d213 | |||
b5928c2f7f | |||
c8e7247d2c | |||
ac6266a23a | |||
88213f67ee | |||
f8fd17f77e | |||
7f127ee515 | |||
ed214b4ac8 | |||
aeb1b450eb | |||
18b4b2d7b2 | |||
a140bad8fb | |||
bb1b8ab7bb | |||
6802614fbf | |||
619113e810 | |||
a8697bf1ad | |||
f52dec4b7e | |||
6560bf18a4 | |||
315cd40e6a | |||
a7a62b5005 | |||
37e3998211 | |||
31be26ebbd | |||
42b1cb06fb | |||
066ec35adf | |||
87a808a747 | |||
d8b1cd757e | |||
b1b9c8e0e5 | |||
a0a617055b | |||
9ec6f548a6 | |||
46980db582 | |||
d8fd1ddec6 | |||
74d29e2374 | |||
801a28ef65 | |||
3fff090612 | |||
b071d55b4d | |||
244cbc5b6d | |||
74da359dd5 | |||
56b73e3bd5 | |||
59e3c85568 | |||
746c933e63 | |||
f165bbca5d | |||
f335b08ec2 | |||
6e831a4253 | |||
6c1687c569 | |||
09c64e2354 | |||
0a312821ee | |||
06d1062423 | |||
dcfa3dc88a | |||
c45bb8e985 | |||
3e4fea875a | |||
c7670d271a | |||
570f3a4d42 | |||
3c54e94c6e | |||
26daaeb57d | |||
a60442fc2c | |||
8790f7059a | |||
49cf10e9bd | |||
13da6f5151 | |||
a1e0564f8f | |||
55f3664063 | |||
baabd8614f | |||
79df24f4eb | |||
f1afc4d263 | |||
643a256f01 | |||
b7f92ef0ea | |||
e33ca93f05 | |||
79af8b8638 | |||
d2b8bd3635 | |||
02e01559f4 | |||
b0c39e4843 | |||
039570a140 | |||
fdc7dedc58 | |||
098fcdeaf2 | |||
3cf9278bea | |||
13ccb352d7 | |||
c5b099856d | |||
6d912be7f6 | |||
0c54d266d3 | |||
c4784cf383 | |||
44ccbe2fdf | |||
d2615f0d6a | |||
5ab3cf4952 | |||
1926a472cd | |||
d220ca6bab | |||
759ea731bf | |||
e01fd5eb1a | |||
e716e24ec6 | |||
e9c84b8bfb | |||
130adf9d26 | |||
6aab505cd7 | |||
a9c597bc08 | |||
853239dff9 | |||
8f8c3e4944 | |||
dde9960b9c | |||
b1e48a6c1a | |||
b704e9031e | |||
15ef5dc792 | |||
6c4a1850b0 | |||
183d036f3c | |||
b324dc0ce2 | |||
6ad7be65ec | |||
8bf335a2a5 | |||
45709770f4 | |||
6158dd80ca | |||
468d26c587 | |||
c39a97ca58 | |||
8f0810ebb3 | |||
98e0f12d17 | |||
8d37e83df7 | |||
a306bb8384 | |||
c80116475b | |||
2997382df2 | |||
65e48907d3 | |||
1c4848ed8f | |||
64f7fa62dd | |||
16abaa8016 | |||
4cc4a3e4b8 | |||
8abe1f61ea | |||
6712095d7e | |||
5ab308bfd7 | |||
8b93fbcc69 | |||
f641670139 | |||
80af26ef50 | |||
64ce170882 | |||
b6171aa1a4 | |||
087582abbd | |||
6b6d88b81b | |||
55e5d36df5 | |||
fc43e841c9 | |||
895ed6fbdc | |||
f3965261c5 | |||
34ee6dc2b7 | |||
55fe4b0bc0 | |||
8d745609f9 | |||
55edb10da0 | |||
66e4b3af36 | |||
d44fc7790e | |||
291972628a | |||
019221c433 | |||
b99fa9f8f8 | |||
5bde2772c3 | |||
10884a7770 | |||
e858d09d28 | |||
856717395e | |||
b7793200de | |||
bcc0323523 | |||
643c1f5bbf | |||
1fca246839 | |||
b73e68a94c | |||
f9d3c4c9a7 | |||
53f8699deb | |||
6f3dc2eafd | |||
567ed07fe8 | |||
2999e9d006 | |||
b32a228e3a | |||
5a2dfb23c6 | |||
8ebce479bd | |||
81589e835e | |||
22b1f39b91 | |||
c25e982f1f | |||
d5c09fae8a | |||
bf15e04053 | |||
0932622567 | |||
0a5b8bea5d | |||
64d4a19ccf | |||
82875cfc0e | |||
83776b9f08 | |||
a742331484 | |||
2e9df96a62 | |||
9f5d7089c3 | |||
ddc78cc297 | |||
cb9b3407d8 | |||
d7b872c1e0 | |||
c35217f581 | |||
3b73a2eb9d | |||
3b94ffa705 | |||
936102f6d9 | |||
8c687d81aa | |||
01d7263484 | |||
49ac0eb662 | |||
8935ca65a7 | |||
58a374d1f1 | |||
f409831921 | |||
951acb26dd | |||
2df0c95806 | |||
f8d1b7b9b7 | |||
e092aabb21 | |||
48c59a815d | |||
9f40716a87 | |||
39da241298 | |||
a71a87fa3e | |||
176fe2f6fc | |||
4544f475c9 | |||
5bbf59b2bd | |||
1b2f1db711 | |||
14fab991b4 | |||
444e0642d0 | |||
89c841b530 | |||
d3ea465d86 | |||
5c38e03820 | |||
3a400da931 | |||
149481f787 | |||
ba368552f2 | |||
fbf0e4a966 | |||
2f7d9a44ad | |||
cad5ff36bd | |||
5024c757fa | |||
68af2e5352 | |||
d21c87eda0 | |||
f20bfc543c | |||
1e69cefd7c | |||
4e64258c91 | |||
4e63f9c250 | |||
0e2ac8afab | |||
33fa159dad | |||
0452eb3e5f | |||
05e3d8db83 | |||
1c9f86e172 | |||
48d1b289a3 | |||
4c23ef4e9e | |||
3c28cf1909 | |||
4a9c95b44e | |||
bcc8d5e76c | |||
85fedec2f6 | |||
bc9984f516 | |||
6ddfe1795c | |||
729ca4f65c | |||
af19b1633a | |||
e385b83318 | |||
b1c396b6d3 | |||
f11b7ca0d8 | |||
55a8db967a | |||
79744df87e | |||
0a662498a7 | |||
b1c38cbb07 | |||
8f2b7f2f49 | |||
52851046ce | |||
8e4929c3b0 | |||
6df28758f0 | |||
7ef14eb86d | |||
e03c25a600 | |||
45de247efd | |||
203dc88bb5 | |||
a01df92007 | |||
cb29d9456f | |||
5bf2bdbb48 | |||
0ad22f7e1c | |||
23c4e150cf | |||
afa1b27582 | |||
ee9d14d32b | |||
30982c833a | |||
ab3f0b50e1 | |||
49e1f4739e | |||
fc35497423 | |||
c379787a90 | |||
97bc679cbb | |||
0ea1c8f138 | |||
9d909a73b2 | |||
c89b7b74e0 | |||
6b629d8a9b | |||
75d602dd90 | |||
fd44bc2bec | |||
35448f6017 | |||
a70363bd95 | |||
40c672f246 | |||
2619562530 | |||
b7b9c521e5 | |||
9c7fd01117 | |||
a12bb1642d | |||
80e8de2548 | |||
0b80f1a7c7 | |||
2698d90637 | |||
633028c8ff | |||
155f1e50b4 | |||
a48e7c17ba | |||
cfb920114a | |||
0bfce6e29d | |||
5139bc9a80 | |||
d24fe25047 | |||
54387a7ab8 | |||
e1fd6cbd31 | |||
a030f04ccb | |||
9d6e58b3d8 | |||
728b64ffc3 | |||
284904a02a | |||
2ec8a445c3 | |||
16b8edd082 | |||
91012b577b | |||
5a5a2a5d69 | |||
d7750d34de | |||
c3ea09a2dd | |||
9f6dca1170 | |||
919a190971 | |||
e5d93a66cc | |||
a57d06b401 | |||
c2909dda1d | |||
a53f25c92f | |||
696f8afcd5 | |||
e2a81df152 | |||
1752c5437c | |||
54b951d3cc | |||
fcf752905b | |||
a4a5b97265 | |||
4087d6892f | |||
2b7e06bb25 | |||
1b2180818e | |||
8c23b390c2 | |||
677e5f3c84 | |||
2b860f19cb | |||
9a583dcd44 | |||
8aae51ab26 | |||
e769f7ee02 | |||
852f6f2819 | |||
6cb6db0bc4 | |||
2e0907af1e | |||
35f29656bc | |||
bb1f18d973 | |||
261eebe127 | |||
8f0ea8dcd9 | |||
eb36c8dd0c | |||
7026760327 | |||
b2349ee99f | |||
d185b3ad70 | |||
8ecf1cadf8 | |||
9961142ab1 | |||
ae299c55c7 | |||
72f60249b8 | |||
d6fed2eaaf | |||
b48ed34ac4 | |||
561691ac22 | |||
0d4511e74b | |||
4e7153c45f | |||
d0a6a067cc | |||
742beda313 | |||
70462c4c72 | |||
7ea721c487 | |||
4d8ee983ef | |||
0bbf37f535 | |||
8e847d05bd | |||
55612a1365 | |||
a1d8b2045d | |||
f1f4cd7d2c | |||
4350bcbe24 | |||
a899495978 | |||
6302ff23d2 | |||
2196bde820 | |||
a861030ecb | |||
c96e195666 | |||
d7d32075e7 | |||
f527700426 | |||
d2bf027c23 | |||
ac1f3332dc | |||
2c64f72ebc | |||
51a8670a13 | |||
b9f6cd9226 | |||
7010682122 | |||
0e82facfb4 | |||
afdff95453 | |||
b11f12b1db | |||
4df906e32c | |||
fee7abed7c | |||
d1a5d0dd7e | |||
d1e06b1c7e | |||
458b2b5c55 | |||
c0b1cd7674 | |||
8305a52ae2 | |||
b77cdfe96b | |||
0dcb261b4c | |||
46bddbf067 | |||
b8b6c0cd98 | |||
64fbbcf3e8 | |||
a4c6b76686 | |||
c8c7f77813 | |||
dde4314127 | |||
0b620f54f3 | |||
dc10ab0e66 | |||
8d92e3d78d | |||
ae66df6d9a | |||
ed3108fbd4 | |||
f2199f1712 | |||
e5810b31c5 | |||
d8b6a06522 | |||
c8ab6c728d | |||
e854623967 | |||
0b4822c1e3 | |||
fcb82c243f | |||
4415bee62a | |||
42b00110e7 | |||
0cce67dd15 | |||
f7a300fb30 | |||
ca260b700f | |||
8e9fbff5bd | |||
f2a8b82249 | |||
11a3cf84fa | |||
d506e5d50c | |||
7f8b8a7eb5 | |||
06af8e3a35 | |||
bf8c3078db | |||
15c7be1979 | |||
285dc8cff0 | |||
d7e399dbf9 | |||
1e25d3e3e9 | |||
d5c0a6e252 | |||
8a5aa9bf6f | |||
6584074b9c | |||
1d773dfc76 | |||
193b9e1ae8 | |||
32f95818db | |||
bcb7c72907 | |||
51a33f330c | |||
da2eddfb5a | |||
75e9a02bd2 | |||
af239027d5 | |||
6ce83e5271 | |||
c804a7e77d | |||
9d9acab603 | |||
8e42eb0546 | |||
f39c0e6bd9 | |||
81ac09695a | |||
26c5653182 | |||
0f7a3875f7 | |||
0036ecf956 | |||
96554de17a | |||
fabd1e39ae | |||
f992bfa8ff | |||
f1a04674fb | |||
ec4c31e37d | |||
ac520cd872 | |||
50e493d692 | |||
d49d8bc559 | |||
3e94b58afb | |||
1b81973358 | |||
880ca9a57d | |||
4d8d12f917 | |||
e78e4165da | |||
e4c7c24ae4 | |||
3b8daf7cc9 | |||
104e70c383 | |||
82ac7d195d | |||
d19d075326 | |||
ae03e4679e | |||
05b0e2c164 | |||
ff5680fb0e | |||
88cf0efb81 | |||
7783b200a3 | |||
d13954970e | |||
743a781eba | |||
f53f3c77be | |||
61b61ce960 | |||
09e6b80fd6 | |||
4cad5f7b40 | |||
3f43ff22a8 | |||
cf6bbbae70 | |||
ac1ef5139c | |||
ce0775239d | |||
56f267146f | |||
d98af5a0b1 | |||
3b3c874175 | |||
1f19e5cb3e | |||
f2062e75a1 | |||
ff5df458af | |||
6a8c5ca650 | |||
01a3516478 | |||
868ce06f67 | |||
e5b6dc5508 | |||
ee86322ab4 | |||
52d19bf4a6 | |||
fdcc1dcb36 | |||
5805ac83f7 | |||
772048092b | |||
be1219a73f | |||
9ab057fafc | |||
f9b6c8cef9 | |||
f159973d8b | |||
4a2f97710e | |||
735a8e77e2 | |||
e50cc20f76 | |||
5c19c6ea7f | |||
4c0b6c71ac | |||
cfc065b41b | |||
d81381bda6 | |||
6613553c13 | |||
9a304cc198 | |||
ebaec17703 | |||
6fcc06bfe0 | |||
2ba66f4f91 | |||
f9fc32e89c | |||
ee275d36bf | |||
ed39123f4e | |||
68726b0921 | |||
74a91aafe8 | |||
a15853ed55 | |||
7c51657aa1 | |||
86e9639d0c | |||
1620131ed5 | |||
743ee53bd9 | |||
7a04d97bdf | |||
6c99194f42 | |||
df8321c282 | |||
9bfbf0ed07 | |||
8f5606edbd | |||
a0f921398f | |||
bf287ab8c4 | |||
cec11f3843 | |||
f66bad43db | |||
b36ed44ca2 | |||
f5aca42e95 | |||
6e9ae69593 | |||
3c0cb1dd12 | |||
de56d02230 | |||
c04e8869f7 | |||
9d60d0b4c5 | |||
a42b181b76 | |||
24657797ad | |||
3981b55b40 | |||
d98471dbea | |||
9cd94f639c | |||
afd950c671 | |||
9328db4c19 | |||
7b40e23840 | |||
8ca7bdcd36 | |||
d51491e1eb | |||
6e1807e51d | |||
785ff6b3df | |||
408016a34e | |||
fc77fa68d1 | |||
48b24e5c65 | |||
b2045fd034 | |||
782e9fadb5 | |||
e48ac56cc5 | |||
f110eda465 | |||
e830d5dc7a | |||
2b1f8ac050 | |||
e8d5d678bf | |||
6df5de861c | |||
c35ae4af3e | |||
ae123a3364 | |||
e155aa5f3e | |||
6fa2765f55 | |||
ecb84dda46 | |||
62e58f2fe9 | |||
0a4e34a142 | |||
1be50bcdb2 | |||
f0c33ef1bf | |||
b059754fe5 | |||
cd4d6483c5 | |||
8dcccb4444 | |||
693da3ee62 | |||
5a9e1a0c94 | |||
a539e4b362 | |||
d13fb1d53d | |||
d9cb82ca6c | |||
8f231e5678 | |||
604242a76c | |||
0d0d33f104 | |||
58907a2b3f | |||
83f6ec86d4 | |||
f832f702cb | |||
2eb55696ed | |||
2ef31322c4 | |||
0d088ae198 | |||
a184240855 | |||
fdd941c84d | |||
419e0adff9 | |||
60a16aafbd | |||
1b24168791 | |||
8909c1e338 | |||
ea7c822d37 | |||
8c183a348f | |||
835208d616 | |||
6ec8143beb | |||
0f57ddefff | |||
dd37e8bf49 | |||
1f733b04f7 | |||
99c03d3073 | |||
dd3b440f8d | |||
feef105acf | |||
ed4154e62d | |||
e6c204cdba | |||
0e83d485a3 | |||
0000f26fee | |||
a74ab9d2c1 | |||
0ca96adaaf | |||
4cea9bfa3f | |||
59b5c21cf6 | |||
05fb11b1f0 | |||
17f9a48252 | |||
4b55746f6c | |||
9836dfcfd4 | |||
6501626692 | |||
184d65cc62 | |||
c93bb4708b | |||
e9d6da6c28 | |||
d7ed1a5d30 | |||
d29c3abc7d | |||
448e0fe067 | |||
faa02afae0 | |||
342eb03731 | |||
58388935b7 | |||
2e451f40e5 | |||
868229a044 | |||
73590572b0 |
@ -1,5 +1,5 @@
|
|||||||
[bumpversion]
|
[bumpversion]
|
||||||
current_version = 2024.2.1
|
current_version = 2024.6.1
|
||||||
tag = True
|
tag = True
|
||||||
commit = True
|
commit = True
|
||||||
parse = (?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)(?:-(?P<rc_t>[a-zA-Z-]+)(?P<rc_n>[1-9]\\d*))?
|
parse = (?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)(?:-(?P<rc_t>[a-zA-Z-]+)(?P<rc_n>[1-9]\\d*))?
|
||||||
@ -17,10 +17,14 @@ optional_value = final
|
|||||||
|
|
||||||
[bumpversion:file:pyproject.toml]
|
[bumpversion:file:pyproject.toml]
|
||||||
|
|
||||||
|
[bumpversion:file:package.json]
|
||||||
|
|
||||||
[bumpversion:file:docker-compose.yml]
|
[bumpversion:file:docker-compose.yml]
|
||||||
|
|
||||||
[bumpversion:file:schema.yml]
|
[bumpversion:file:schema.yml]
|
||||||
|
|
||||||
|
[bumpversion:file:blueprints/schema.json]
|
||||||
|
|
||||||
[bumpversion:file:authentik/__init__.py]
|
[bumpversion:file:authentik/__init__.py]
|
||||||
|
|
||||||
[bumpversion:file:internal/constants/constants.go]
|
[bumpversion:file:internal/constants/constants.go]
|
||||||
|
2
.github/FUNDING.yml
vendored
2
.github/FUNDING.yml
vendored
@ -1 +1 @@
|
|||||||
github: [BeryJu]
|
custom: https://goauthentik.io/pricing/
|
||||||
|
2
.github/ISSUE_TEMPLATE/question.md
vendored
2
.github/ISSUE_TEMPLATE/question.md
vendored
@ -9,7 +9,7 @@ assignees: ""
|
|||||||
**Describe your question/**
|
**Describe your question/**
|
||||||
A clear and concise description of what you're trying to do.
|
A clear and concise description of what you're trying to do.
|
||||||
|
|
||||||
**Relevant infos**
|
**Relevant info**
|
||||||
i.e. Version of other software you're using, specifics of your setup
|
i.e. Version of other software you're using, specifics of your setup
|
||||||
|
|
||||||
**Screenshots**
|
**Screenshots**
|
||||||
|
@ -54,9 +54,10 @@ runs:
|
|||||||
authentik:
|
authentik:
|
||||||
outposts:
|
outposts:
|
||||||
container_image_base: ghcr.io/goauthentik/dev-%(type)s:gh-%(build_hash)s
|
container_image_base: ghcr.io/goauthentik/dev-%(type)s:gh-%(build_hash)s
|
||||||
image:
|
global:
|
||||||
repository: ghcr.io/goauthentik/dev-server
|
image:
|
||||||
tag: ${{ inputs.tag }}
|
repository: ghcr.io/goauthentik/dev-server
|
||||||
|
tag: ${{ inputs.tag }}
|
||||||
```
|
```
|
||||||
|
|
||||||
For arm64, use these values:
|
For arm64, use these values:
|
||||||
@ -65,9 +66,10 @@ runs:
|
|||||||
authentik:
|
authentik:
|
||||||
outposts:
|
outposts:
|
||||||
container_image_base: ghcr.io/goauthentik/dev-%(type)s:gh-%(build_hash)s
|
container_image_base: ghcr.io/goauthentik/dev-%(type)s:gh-%(build_hash)s
|
||||||
image:
|
global:
|
||||||
repository: ghcr.io/goauthentik/dev-server
|
image:
|
||||||
tag: ${{ inputs.tag }}-arm64
|
repository: ghcr.io/goauthentik/dev-server
|
||||||
|
tag: ${{ inputs.tag }}-arm64
|
||||||
```
|
```
|
||||||
|
|
||||||
Afterwards, run the upgrade commands from the latest release notes.
|
Afterwards, run the upgrade commands from the latest release notes.
|
||||||
|
@ -11,6 +11,10 @@ inputs:
|
|||||||
description: "Docker image arch"
|
description: "Docker image arch"
|
||||||
|
|
||||||
outputs:
|
outputs:
|
||||||
|
shouldBuild:
|
||||||
|
description: "Whether to build image or not"
|
||||||
|
value: ${{ steps.ev.outputs.shouldBuild }}
|
||||||
|
|
||||||
sha:
|
sha:
|
||||||
description: "sha"
|
description: "sha"
|
||||||
value: ${{ steps.ev.outputs.sha }}
|
value: ${{ steps.ev.outputs.sha }}
|
||||||
|
@ -7,10 +7,12 @@ from time import time
|
|||||||
parser = configparser.ConfigParser()
|
parser = configparser.ConfigParser()
|
||||||
parser.read(".bumpversion.cfg")
|
parser.read(".bumpversion.cfg")
|
||||||
|
|
||||||
|
should_build = str(os.environ.get("DOCKER_USERNAME", None) is not None).lower()
|
||||||
|
|
||||||
branch_name = os.environ["GITHUB_REF"]
|
branch_name = os.environ["GITHUB_REF"]
|
||||||
if os.environ.get("GITHUB_HEAD_REF", "") != "":
|
if os.environ.get("GITHUB_HEAD_REF", "") != "":
|
||||||
branch_name = os.environ["GITHUB_HEAD_REF"]
|
branch_name = os.environ["GITHUB_HEAD_REF"]
|
||||||
safe_branch_name = branch_name.replace("refs/heads/", "").replace("/", "-")
|
safe_branch_name = branch_name.replace("refs/heads/", "").replace("/", "-").replace("'", "-")
|
||||||
|
|
||||||
image_names = os.getenv("IMAGE_NAME").split(",")
|
image_names = os.getenv("IMAGE_NAME").split(",")
|
||||||
image_arch = os.getenv("IMAGE_ARCH") or None
|
image_arch = os.getenv("IMAGE_ARCH") or None
|
||||||
@ -52,8 +54,9 @@ image_main_tag = image_tags[0]
|
|||||||
image_tags_rendered = ",".join(image_tags)
|
image_tags_rendered = ",".join(image_tags)
|
||||||
|
|
||||||
with open(os.environ["GITHUB_OUTPUT"], "a+", encoding="utf-8") as _output:
|
with open(os.environ["GITHUB_OUTPUT"], "a+", encoding="utf-8") as _output:
|
||||||
print("sha=%s" % sha, file=_output)
|
print(f"shouldBuild={should_build}", file=_output)
|
||||||
print("version=%s" % version, file=_output)
|
print(f"sha={sha}", file=_output)
|
||||||
print("prerelease=%s" % prerelease, file=_output)
|
print(f"version={version}", file=_output)
|
||||||
print("imageTags=%s" % image_tags_rendered, file=_output)
|
print(f"prerelease={prerelease}", file=_output)
|
||||||
print("imageMainTag=%s" % image_main_tag, file=_output)
|
print(f"imageTags={image_tags_rendered}", file=_output)
|
||||||
|
print(f"imageMainTag={image_main_tag}", file=_output)
|
||||||
|
8
.github/actions/setup/action.yml
vendored
8
.github/actions/setup/action.yml
vendored
@ -16,25 +16,25 @@ runs:
|
|||||||
sudo apt-get update
|
sudo apt-get update
|
||||||
sudo apt-get install --no-install-recommends -y libpq-dev openssl libxmlsec1-dev pkg-config gettext
|
sudo apt-get install --no-install-recommends -y libpq-dev openssl libxmlsec1-dev pkg-config gettext
|
||||||
- name: Setup python and restore poetry
|
- name: Setup python and restore poetry
|
||||||
uses: actions/setup-python@v4
|
uses: actions/setup-python@v5
|
||||||
with:
|
with:
|
||||||
python-version-file: "pyproject.toml"
|
python-version-file: "pyproject.toml"
|
||||||
cache: "poetry"
|
cache: "poetry"
|
||||||
- name: Setup node
|
- name: Setup node
|
||||||
uses: actions/setup-node@v3
|
uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version-file: web/package.json
|
node-version-file: web/package.json
|
||||||
cache: "npm"
|
cache: "npm"
|
||||||
cache-dependency-path: web/package-lock.json
|
cache-dependency-path: web/package-lock.json
|
||||||
- name: Setup go
|
- name: Setup go
|
||||||
uses: actions/setup-go@v4
|
uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
go-version-file: "go.mod"
|
go-version-file: "go.mod"
|
||||||
- name: Setup dependencies
|
- name: Setup dependencies
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
export PSQL_TAG=${{ inputs.postgresql_version }}
|
export PSQL_TAG=${{ inputs.postgresql_version }}
|
||||||
docker-compose -f .github/actions/setup/docker-compose.yml up -d
|
docker compose -f .github/actions/setup/docker-compose.yml up -d
|
||||||
poetry install
|
poetry install
|
||||||
cd web && npm ci
|
cd web && npm ci
|
||||||
- name: Generate config
|
- name: Generate config
|
||||||
|
2
.github/actions/setup/docker-compose.yml
vendored
2
.github/actions/setup/docker-compose.yml
vendored
@ -1,5 +1,3 @@
|
|||||||
version: "3.7"
|
|
||||||
|
|
||||||
services:
|
services:
|
||||||
postgresql:
|
postgresql:
|
||||||
image: docker.io/library/postgres:${PSQL_TAG:-16}
|
image: docker.io/library/postgres:${PSQL_TAG:-16}
|
||||||
|
1
.github/codespell-words.txt
vendored
1
.github/codespell-words.txt
vendored
@ -4,3 +4,4 @@ hass
|
|||||||
warmup
|
warmup
|
||||||
ontext
|
ontext
|
||||||
singed
|
singed
|
||||||
|
assertIn
|
||||||
|
40
.github/dependabot.yml
vendored
40
.github/dependabot.yml
vendored
@ -21,7 +21,10 @@ updates:
|
|||||||
labels:
|
labels:
|
||||||
- dependencies
|
- dependencies
|
||||||
- package-ecosystem: npm
|
- package-ecosystem: npm
|
||||||
directory: "/web"
|
directories:
|
||||||
|
- "/web"
|
||||||
|
- "/tests/wdio"
|
||||||
|
- "/web/sfe"
|
||||||
schedule:
|
schedule:
|
||||||
interval: daily
|
interval: daily
|
||||||
time: "04:00"
|
time: "04:00"
|
||||||
@ -30,7 +33,6 @@ updates:
|
|||||||
open-pull-requests-limit: 10
|
open-pull-requests-limit: 10
|
||||||
commit-message:
|
commit-message:
|
||||||
prefix: "web:"
|
prefix: "web:"
|
||||||
# TODO: deduplicate these groups
|
|
||||||
groups:
|
groups:
|
||||||
sentry:
|
sentry:
|
||||||
patterns:
|
patterns:
|
||||||
@ -52,38 +54,10 @@ updates:
|
|||||||
esbuild:
|
esbuild:
|
||||||
patterns:
|
patterns:
|
||||||
- "@esbuild/*"
|
- "@esbuild/*"
|
||||||
- package-ecosystem: npm
|
rollup:
|
||||||
directory: "/tests/wdio"
|
|
||||||
schedule:
|
|
||||||
interval: daily
|
|
||||||
time: "04:00"
|
|
||||||
labels:
|
|
||||||
- dependencies
|
|
||||||
open-pull-requests-limit: 10
|
|
||||||
commit-message:
|
|
||||||
prefix: "web:"
|
|
||||||
# TODO: deduplicate these groups
|
|
||||||
groups:
|
|
||||||
sentry:
|
|
||||||
patterns:
|
patterns:
|
||||||
- "@sentry/*"
|
- "@rollup/*"
|
||||||
- "@spotlightjs/*"
|
- "rollup-*"
|
||||||
babel:
|
|
||||||
patterns:
|
|
||||||
- "@babel/*"
|
|
||||||
- "babel-*"
|
|
||||||
eslint:
|
|
||||||
patterns:
|
|
||||||
- "@typescript-eslint/*"
|
|
||||||
- "eslint"
|
|
||||||
- "eslint-*"
|
|
||||||
storybook:
|
|
||||||
patterns:
|
|
||||||
- "@storybook/*"
|
|
||||||
- "*storybook*"
|
|
||||||
esbuild:
|
|
||||||
patterns:
|
|
||||||
- "@esbuild/*"
|
|
||||||
wdio:
|
wdio:
|
||||||
patterns:
|
patterns:
|
||||||
- "@wdio/*"
|
- "@wdio/*"
|
||||||
|
65
.github/workflows/api-py-publish.yml
vendored
Normal file
65
.github/workflows/api-py-publish.yml
vendored
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
name: authentik-api-py-publish
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
paths:
|
||||||
|
- "schema.yml"
|
||||||
|
workflow_dispatch:
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
id-token: write
|
||||||
|
steps:
|
||||||
|
- id: generate_token
|
||||||
|
uses: tibdex/github-app-token@v2
|
||||||
|
with:
|
||||||
|
app_id: ${{ secrets.GH_APP_ID }}
|
||||||
|
private_key: ${{ secrets.GH_APP_PRIVATE_KEY }}
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
token: ${{ steps.generate_token.outputs.token }}
|
||||||
|
- name: Install poetry & deps
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
pipx install poetry || true
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install --no-install-recommends -y libpq-dev openssl libxmlsec1-dev pkg-config gettext
|
||||||
|
- name: Setup python and restore poetry
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version-file: "pyproject.toml"
|
||||||
|
cache: "poetry"
|
||||||
|
- name: Generate API Client
|
||||||
|
run: make gen-client-py
|
||||||
|
- name: Publish package
|
||||||
|
working-directory: gen-py-api/
|
||||||
|
run: |
|
||||||
|
poetry build
|
||||||
|
- name: Publish package to PyPI
|
||||||
|
uses: pypa/gh-action-pypi-publish@release/v1
|
||||||
|
with:
|
||||||
|
packages-dir: gen-py-api/dist/
|
||||||
|
# We can't easily upgrade the API client being used due to poetry being poetry
|
||||||
|
# so we'll have to rely on dependabot
|
||||||
|
# - name: Upgrade /
|
||||||
|
# run: |
|
||||||
|
# export VERSION=$(cd gen-py-api && poetry version -s)
|
||||||
|
# poetry add "authentik_client=$VERSION" --allow-prereleases --lock
|
||||||
|
# - uses: peter-evans/create-pull-request@v6
|
||||||
|
# id: cpr
|
||||||
|
# with:
|
||||||
|
# token: ${{ steps.generate_token.outputs.token }}
|
||||||
|
# branch: update-root-api-client
|
||||||
|
# commit-message: "root: bump API Client version"
|
||||||
|
# title: "root: bump API Client version"
|
||||||
|
# body: "root: bump API Client version"
|
||||||
|
# delete-branch: true
|
||||||
|
# signoff: true
|
||||||
|
# # ID from https://api.github.com/users/authentik-automation[bot]
|
||||||
|
# author: authentik-automation[bot] <135050075+authentik-automation[bot]@users.noreply.github.com>
|
||||||
|
# - uses: peter-evans/enable-pull-request-automerge@v3
|
||||||
|
# with:
|
||||||
|
# token: ${{ steps.generate_token.outputs.token }}
|
||||||
|
# pull-request-number: ${{ steps.cpr.outputs.pull-request-number }}
|
||||||
|
# merge-method: squash
|
@ -1,4 +1,4 @@
|
|||||||
name: authentik-web-api-publish
|
name: authentik-api-ts-publish
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [main]
|
branches: [main]
|
||||||
@ -31,7 +31,12 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_PUBLISH_TOKEN }}
|
NODE_AUTH_TOKEN: ${{ secrets.NPM_PUBLISH_TOKEN }}
|
||||||
- name: Upgrade /web
|
- name: Upgrade /web
|
||||||
working-directory: web/
|
working-directory: web
|
||||||
|
run: |
|
||||||
|
export VERSION=`node -e 'console.log(require("../gen-ts-api/package.json").version)'`
|
||||||
|
npm i @goauthentik/api@$VERSION
|
||||||
|
- name: Upgrade /web/sfe
|
||||||
|
working-directory: web/sfe
|
||||||
run: |
|
run: |
|
||||||
export VERSION=`node -e 'console.log(require("../gen-ts-api/package.json").version)'`
|
export VERSION=`node -e 'console.log(require("../gen-ts-api/package.json").version)'`
|
||||||
npm i @goauthentik/api@$VERSION
|
npm i @goauthentik/api@$VERSION
|
26
.github/workflows/ci-main.yml
vendored
26
.github/workflows/ci-main.yml
vendored
@ -7,8 +7,6 @@ on:
|
|||||||
- main
|
- main
|
||||||
- next
|
- next
|
||||||
- version-*
|
- version-*
|
||||||
paths-ignore:
|
|
||||||
- website/**
|
|
||||||
pull_request:
|
pull_request:
|
||||||
branches:
|
branches:
|
||||||
- main
|
- main
|
||||||
@ -52,7 +50,6 @@ jobs:
|
|||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
psql:
|
psql:
|
||||||
- 12-alpine
|
|
||||||
- 15-alpine
|
- 15-alpine
|
||||||
- 16-alpine
|
- 16-alpine
|
||||||
steps:
|
steps:
|
||||||
@ -106,7 +103,6 @@ jobs:
|
|||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
psql:
|
psql:
|
||||||
- 12-alpine
|
|
||||||
- 15-alpine
|
- 15-alpine
|
||||||
- 16-alpine
|
- 16-alpine
|
||||||
steps:
|
steps:
|
||||||
@ -132,7 +128,7 @@ jobs:
|
|||||||
- name: Setup authentik env
|
- name: Setup authentik env
|
||||||
uses: ./.github/actions/setup
|
uses: ./.github/actions/setup
|
||||||
- name: Create k8s Kind Cluster
|
- name: Create k8s Kind Cluster
|
||||||
uses: helm/kind-action@v1.9.0
|
uses: helm/kind-action@v1.10.0
|
||||||
- name: run integration
|
- name: run integration
|
||||||
run: |
|
run: |
|
||||||
poetry run coverage run manage.py test tests/integration
|
poetry run coverage run manage.py test tests/integration
|
||||||
@ -162,6 +158,8 @@ jobs:
|
|||||||
glob: tests/e2e/test_provider_ldap* tests/e2e/test_source_ldap*
|
glob: tests/e2e/test_provider_ldap* tests/e2e/test_source_ldap*
|
||||||
- name: radius
|
- name: radius
|
||||||
glob: tests/e2e/test_provider_radius*
|
glob: tests/e2e/test_provider_radius*
|
||||||
|
- name: scim
|
||||||
|
glob: tests/e2e/test_source_scim*
|
||||||
- name: flows
|
- name: flows
|
||||||
glob: tests/e2e/test_flows*
|
glob: tests/e2e/test_flows*
|
||||||
steps:
|
steps:
|
||||||
@ -170,7 +168,7 @@ jobs:
|
|||||||
uses: ./.github/actions/setup
|
uses: ./.github/actions/setup
|
||||||
- name: Setup e2e env (chrome, etc)
|
- name: Setup e2e env (chrome, etc)
|
||||||
run: |
|
run: |
|
||||||
docker-compose -f tests/e2e/docker-compose.yml up -d
|
docker compose -f tests/e2e/docker-compose.yml up -d
|
||||||
- id: cache-web
|
- id: cache-web
|
||||||
uses: actions/cache@v4
|
uses: actions/cache@v4
|
||||||
with:
|
with:
|
||||||
@ -216,22 +214,24 @@ jobs:
|
|||||||
# Needed to upload contianer images to ghcr.io
|
# Needed to upload contianer images to ghcr.io
|
||||||
packages: write
|
packages: write
|
||||||
timeout-minutes: 120
|
timeout-minutes: 120
|
||||||
if: "github.repository == 'goauthentik/authentik'"
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
ref: ${{ github.event.pull_request.head.sha }}
|
ref: ${{ github.event.pull_request.head.sha }}
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@v3.0.0
|
uses: docker/setup-qemu-action@v3.1.0
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v3
|
uses: docker/setup-buildx-action@v3
|
||||||
- name: prepare variables
|
- name: prepare variables
|
||||||
uses: ./.github/actions/docker-push-variables
|
uses: ./.github/actions/docker-push-variables
|
||||||
id: ev
|
id: ev
|
||||||
|
env:
|
||||||
|
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
||||||
with:
|
with:
|
||||||
image-name: ghcr.io/goauthentik/dev-server
|
image-name: ghcr.io/goauthentik/dev-server
|
||||||
image-arch: ${{ matrix.arch }}
|
image-arch: ${{ matrix.arch }}
|
||||||
- name: Login to Container Registry
|
- name: Login to Container Registry
|
||||||
|
if: ${{ steps.ev.outputs.shouldBuild == 'true' }}
|
||||||
uses: docker/login-action@v3
|
uses: docker/login-action@v3
|
||||||
with:
|
with:
|
||||||
registry: ghcr.io
|
registry: ghcr.io
|
||||||
@ -240,18 +240,18 @@ jobs:
|
|||||||
- name: generate ts client
|
- name: generate ts client
|
||||||
run: make gen-client-ts
|
run: make gen-client-ts
|
||||||
- name: Build Docker Image
|
- name: Build Docker Image
|
||||||
uses: docker/build-push-action@v5
|
uses: docker/build-push-action@v6
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
secrets: |
|
secrets: |
|
||||||
GEOIPUPDATE_ACCOUNT_ID=${{ secrets.GEOIPUPDATE_ACCOUNT_ID }}
|
GEOIPUPDATE_ACCOUNT_ID=${{ secrets.GEOIPUPDATE_ACCOUNT_ID }}
|
||||||
GEOIPUPDATE_LICENSE_KEY=${{ secrets.GEOIPUPDATE_LICENSE_KEY }}
|
GEOIPUPDATE_LICENSE_KEY=${{ secrets.GEOIPUPDATE_LICENSE_KEY }}
|
||||||
tags: ${{ steps.ev.outputs.imageTags }}
|
tags: ${{ steps.ev.outputs.imageTags }}
|
||||||
push: true
|
push: ${{ steps.ev.outputs.shouldBuild == 'true' }}
|
||||||
build-args: |
|
build-args: |
|
||||||
GIT_BUILD_HASH=${{ steps.ev.outputs.sha }}
|
GIT_BUILD_HASH=${{ steps.ev.outputs.sha }}
|
||||||
cache-from: type=gha
|
cache-from: type=registry,ref=ghcr.io/goauthentik/dev-server:buildcache
|
||||||
cache-to: type=gha,mode=max
|
cache-to: type=registry,ref=ghcr.io/goauthentik/dev-server:buildcache,mode=max
|
||||||
platforms: linux/${{ matrix.arch }}
|
platforms: linux/${{ matrix.arch }}
|
||||||
pr-comment:
|
pr-comment:
|
||||||
needs:
|
needs:
|
||||||
@ -269,6 +269,8 @@ jobs:
|
|||||||
- name: prepare variables
|
- name: prepare variables
|
||||||
uses: ./.github/actions/docker-push-variables
|
uses: ./.github/actions/docker-push-variables
|
||||||
id: ev
|
id: ev
|
||||||
|
env:
|
||||||
|
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
||||||
with:
|
with:
|
||||||
image-name: ghcr.io/goauthentik/dev-server
|
image-name: ghcr.io/goauthentik/dev-server
|
||||||
- name: Comment on PR
|
- name: Comment on PR
|
||||||
|
16
.github/workflows/ci-outpost.yml
vendored
16
.github/workflows/ci-outpost.yml
vendored
@ -29,7 +29,7 @@ jobs:
|
|||||||
- name: Generate API
|
- name: Generate API
|
||||||
run: make gen-client-go
|
run: make gen-client-go
|
||||||
- name: golangci-lint
|
- name: golangci-lint
|
||||||
uses: golangci/golangci-lint-action@v4
|
uses: golangci/golangci-lint-action@v6
|
||||||
with:
|
with:
|
||||||
version: v1.54.2
|
version: v1.54.2
|
||||||
args: --timeout 5000s --verbose
|
args: --timeout 5000s --verbose
|
||||||
@ -71,21 +71,23 @@ jobs:
|
|||||||
permissions:
|
permissions:
|
||||||
# Needed to upload contianer images to ghcr.io
|
# Needed to upload contianer images to ghcr.io
|
||||||
packages: write
|
packages: write
|
||||||
if: "github.repository == 'goauthentik/authentik'"
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
ref: ${{ github.event.pull_request.head.sha }}
|
ref: ${{ github.event.pull_request.head.sha }}
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@v3.0.0
|
uses: docker/setup-qemu-action@v3.1.0
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v3
|
uses: docker/setup-buildx-action@v3
|
||||||
- name: prepare variables
|
- name: prepare variables
|
||||||
uses: ./.github/actions/docker-push-variables
|
uses: ./.github/actions/docker-push-variables
|
||||||
id: ev
|
id: ev
|
||||||
|
env:
|
||||||
|
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
||||||
with:
|
with:
|
||||||
image-name: ghcr.io/goauthentik/dev-${{ matrix.type }}
|
image-name: ghcr.io/goauthentik/dev-${{ matrix.type }}
|
||||||
- name: Login to Container Registry
|
- name: Login to Container Registry
|
||||||
|
if: ${{ steps.ev.outputs.shouldBuild == 'true' }}
|
||||||
uses: docker/login-action@v3
|
uses: docker/login-action@v3
|
||||||
with:
|
with:
|
||||||
registry: ghcr.io
|
registry: ghcr.io
|
||||||
@ -94,17 +96,17 @@ jobs:
|
|||||||
- name: Generate API
|
- name: Generate API
|
||||||
run: make gen-client-go
|
run: make gen-client-go
|
||||||
- name: Build Docker Image
|
- name: Build Docker Image
|
||||||
uses: docker/build-push-action@v5
|
uses: docker/build-push-action@v6
|
||||||
with:
|
with:
|
||||||
tags: ${{ steps.ev.outputs.imageTags }}
|
tags: ${{ steps.ev.outputs.imageTags }}
|
||||||
file: ${{ matrix.type }}.Dockerfile
|
file: ${{ matrix.type }}.Dockerfile
|
||||||
push: true
|
push: ${{ steps.ev.outputs.shouldBuild == 'true' }}
|
||||||
build-args: |
|
build-args: |
|
||||||
GIT_BUILD_HASH=${{ steps.ev.outputs.sha }}
|
GIT_BUILD_HASH=${{ steps.ev.outputs.sha }}
|
||||||
platforms: linux/amd64,linux/arm64
|
platforms: linux/amd64,linux/arm64
|
||||||
context: .
|
context: .
|
||||||
cache-from: type=gha
|
cache-from: type=registry,ref=ghcr.io/goauthentik/dev-${{ matrix.type }}:buildcache
|
||||||
cache-to: type=gha,mode=max
|
cache-to: type=registry,ref=ghcr.io/goauthentik/dev-${{ matrix.type }}:buildcache,mode=max
|
||||||
build-binary:
|
build-binary:
|
||||||
timeout-minutes: 120
|
timeout-minutes: 120
|
||||||
needs:
|
needs:
|
||||||
|
112
.github/workflows/ci-web.yml
vendored
112
.github/workflows/ci-web.yml
vendored
@ -12,14 +12,36 @@ on:
|
|||||||
- version-*
|
- version-*
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
lint-eslint:
|
lint:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
|
command:
|
||||||
|
- lint
|
||||||
|
- lint:lockfile
|
||||||
|
- tsc
|
||||||
|
- prettier-check
|
||||||
project:
|
project:
|
||||||
- web
|
- web
|
||||||
- tests/wdio
|
- tests/wdio
|
||||||
|
include:
|
||||||
|
- command: tsc
|
||||||
|
project: web
|
||||||
|
extra_setup: |
|
||||||
|
cd sfe/ && npm ci
|
||||||
|
- command: lit-analyse
|
||||||
|
project: web
|
||||||
|
extra_setup: |
|
||||||
|
# lit-analyse doesn't understand path rewrites, so make it
|
||||||
|
# belive it's an actual module
|
||||||
|
cd node_modules/@goauthentik
|
||||||
|
ln -s ../../src/ web
|
||||||
|
exclude:
|
||||||
|
- command: lint:lockfile
|
||||||
|
project: tests/wdio
|
||||||
|
- command: tsc
|
||||||
|
project: tests/wdio
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
@ -28,77 +50,17 @@ jobs:
|
|||||||
cache: "npm"
|
cache: "npm"
|
||||||
cache-dependency-path: ${{ matrix.project }}/package-lock.json
|
cache-dependency-path: ${{ matrix.project }}/package-lock.json
|
||||||
- working-directory: ${{ matrix.project }}/
|
- working-directory: ${{ matrix.project }}/
|
||||||
run: npm ci
|
|
||||||
- name: Generate API
|
|
||||||
run: make gen-client-ts
|
|
||||||
- name: Eslint
|
|
||||||
working-directory: ${{ matrix.project }}/
|
|
||||||
run: npm run lint
|
|
||||||
lint-build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version-file: web/package.json
|
|
||||||
cache: "npm"
|
|
||||||
cache-dependency-path: web/package-lock.json
|
|
||||||
- working-directory: web/
|
|
||||||
run: npm ci
|
|
||||||
- name: Generate API
|
|
||||||
run: make gen-client-ts
|
|
||||||
- name: TSC
|
|
||||||
working-directory: web/
|
|
||||||
run: npm run tsc
|
|
||||||
lint-prettier:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
project:
|
|
||||||
- web
|
|
||||||
- tests/wdio
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version-file: ${{ matrix.project }}/package.json
|
|
||||||
cache: "npm"
|
|
||||||
cache-dependency-path: ${{ matrix.project }}/package-lock.json
|
|
||||||
- working-directory: ${{ matrix.project }}/
|
|
||||||
run: npm ci
|
|
||||||
- name: Generate API
|
|
||||||
run: make gen-client-ts
|
|
||||||
- name: prettier
|
|
||||||
working-directory: ${{ matrix.project }}/
|
|
||||||
run: npm run prettier-check
|
|
||||||
lint-lit-analyse:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version-file: web/package.json
|
|
||||||
cache: "npm"
|
|
||||||
cache-dependency-path: web/package-lock.json
|
|
||||||
- working-directory: web/
|
|
||||||
run: |
|
run: |
|
||||||
npm ci
|
npm ci
|
||||||
# lit-analyse doesn't understand path rewrites, so make it
|
${{ matrix.extra_setup }}
|
||||||
# belive it's an actual module
|
|
||||||
cd node_modules/@goauthentik
|
|
||||||
ln -s ../../src/ web
|
|
||||||
- name: Generate API
|
- name: Generate API
|
||||||
run: make gen-client-ts
|
run: make gen-client-ts
|
||||||
- name: lit-analyse
|
- name: Lint
|
||||||
working-directory: web/
|
working-directory: ${{ matrix.project }}/
|
||||||
run: npm run lit-analyse
|
run: npm run ${{ matrix.command }}
|
||||||
ci-web-mark:
|
ci-web-mark:
|
||||||
needs:
|
needs:
|
||||||
- lint-eslint
|
- lint
|
||||||
- lint-prettier
|
|
||||||
- lint-lit-analyse
|
|
||||||
- lint-build
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- run: echo mark
|
- run: echo mark
|
||||||
@ -120,3 +82,21 @@ jobs:
|
|||||||
- name: build
|
- name: build
|
||||||
working-directory: web/
|
working-directory: web/
|
||||||
run: npm run build
|
run: npm run build
|
||||||
|
test:
|
||||||
|
needs:
|
||||||
|
- ci-web-mark
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version-file: web/package.json
|
||||||
|
cache: "npm"
|
||||||
|
cache-dependency-path: web/package-lock.json
|
||||||
|
- working-directory: web/
|
||||||
|
run: npm ci
|
||||||
|
- name: Generate API
|
||||||
|
run: make gen-client-ts
|
||||||
|
- name: test
|
||||||
|
working-directory: web/
|
||||||
|
run: npm run test
|
||||||
|
20
.github/workflows/ci-website.yml
vendored
20
.github/workflows/ci-website.yml
vendored
@ -12,20 +12,21 @@ on:
|
|||||||
- version-*
|
- version-*
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
lint-prettier:
|
lint:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
command:
|
||||||
|
- lint:lockfile
|
||||||
|
- prettier-check
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version-file: website/package.json
|
|
||||||
cache: "npm"
|
|
||||||
cache-dependency-path: website/package-lock.json
|
|
||||||
- working-directory: website/
|
- working-directory: website/
|
||||||
run: npm ci
|
run: npm ci
|
||||||
- name: prettier
|
- name: Lint
|
||||||
working-directory: website/
|
working-directory: website/
|
||||||
run: npm run prettier-check
|
run: npm run ${{ matrix.command }}
|
||||||
test:
|
test:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
@ -48,7 +49,6 @@ jobs:
|
|||||||
matrix:
|
matrix:
|
||||||
job:
|
job:
|
||||||
- build
|
- build
|
||||||
- build-docs-only
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
@ -63,7 +63,7 @@ jobs:
|
|||||||
run: npm run ${{ matrix.job }}
|
run: npm run ${{ matrix.job }}
|
||||||
ci-website-mark:
|
ci-website-mark:
|
||||||
needs:
|
needs:
|
||||||
- lint-prettier
|
- lint
|
||||||
- test
|
- test
|
||||||
- build
|
- build
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
43
.github/workflows/gen-update-webauthn-mds.yml
vendored
Normal file
43
.github/workflows/gen-update-webauthn-mds.yml
vendored
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
name: authentik-gen-update-webauthn-mds
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
schedule:
|
||||||
|
- cron: '30 1 1,15 * *'
|
||||||
|
|
||||||
|
env:
|
||||||
|
POSTGRES_DB: authentik
|
||||||
|
POSTGRES_USER: authentik
|
||||||
|
POSTGRES_PASSWORD: "EK-5jnKfjrGRm<77"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- id: generate_token
|
||||||
|
uses: tibdex/github-app-token@v2
|
||||||
|
with:
|
||||||
|
app_id: ${{ secrets.GH_APP_ID }}
|
||||||
|
private_key: ${{ secrets.GH_APP_PRIVATE_KEY }}
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
token: ${{ steps.generate_token.outputs.token }}
|
||||||
|
- name: Setup authentik env
|
||||||
|
uses: ./.github/actions/setup
|
||||||
|
- run: poetry run ak update_webauthn_mds
|
||||||
|
- uses: peter-evans/create-pull-request@v6
|
||||||
|
id: cpr
|
||||||
|
with:
|
||||||
|
token: ${{ steps.generate_token.outputs.token }}
|
||||||
|
branch: update-fido-mds-client
|
||||||
|
commit-message: "stages/authenticator_webauthn: Update FIDO MDS3 & Passkey aaguid blobs"
|
||||||
|
title: "stages/authenticator_webauthn: Update FIDO MDS3 & Passkey aaguid blobs"
|
||||||
|
body: "stages/authenticator_webauthn: Update FIDO MDS3 & Passkey aaguid blobs"
|
||||||
|
delete-branch: true
|
||||||
|
signoff: true
|
||||||
|
# ID from https://api.github.com/users/authentik-automation[bot]
|
||||||
|
author: authentik-automation[bot] <135050075+authentik-automation[bot]@users.noreply.github.com>
|
||||||
|
- uses: peter-evans/enable-pull-request-automerge@v3
|
||||||
|
with:
|
||||||
|
token: ${{ steps.generate_token.outputs.token }}
|
||||||
|
pull-request-number: ${{ steps.cpr.outputs.pull-request-number }}
|
||||||
|
merge-method: squash
|
26
.github/workflows/release-publish.yml
vendored
26
.github/workflows/release-publish.yml
vendored
@ -14,12 +14,14 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@v3.0.0
|
uses: docker/setup-qemu-action@v3.1.0
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v3
|
uses: docker/setup-buildx-action@v3
|
||||||
- name: prepare variables
|
- name: prepare variables
|
||||||
uses: ./.github/actions/docker-push-variables
|
uses: ./.github/actions/docker-push-variables
|
||||||
id: ev
|
id: ev
|
||||||
|
env:
|
||||||
|
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
||||||
with:
|
with:
|
||||||
image-name: ghcr.io/goauthentik/server,beryju/authentik
|
image-name: ghcr.io/goauthentik/server,beryju/authentik
|
||||||
- name: Docker Login Registry
|
- name: Docker Login Registry
|
||||||
@ -38,7 +40,7 @@ jobs:
|
|||||||
mkdir -p ./gen-ts-api
|
mkdir -p ./gen-ts-api
|
||||||
mkdir -p ./gen-go-api
|
mkdir -p ./gen-go-api
|
||||||
- name: Build Docker Image
|
- name: Build Docker Image
|
||||||
uses: docker/build-push-action@v5
|
uses: docker/build-push-action@v6
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
push: true
|
push: true
|
||||||
@ -66,12 +68,14 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
go-version-file: "go.mod"
|
go-version-file: "go.mod"
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@v3.0.0
|
uses: docker/setup-qemu-action@v3.1.0
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v3
|
uses: docker/setup-buildx-action@v3
|
||||||
- name: prepare variables
|
- name: prepare variables
|
||||||
uses: ./.github/actions/docker-push-variables
|
uses: ./.github/actions/docker-push-variables
|
||||||
id: ev
|
id: ev
|
||||||
|
env:
|
||||||
|
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
||||||
with:
|
with:
|
||||||
image-name: ghcr.io/goauthentik/${{ matrix.type }},beryju/authentik-${{ matrix.type }}
|
image-name: ghcr.io/goauthentik/${{ matrix.type }},beryju/authentik-${{ matrix.type }}
|
||||||
- name: make empty clients
|
- name: make empty clients
|
||||||
@ -90,7 +94,7 @@ jobs:
|
|||||||
username: ${{ github.repository_owner }}
|
username: ${{ github.repository_owner }}
|
||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
- name: Build Docker Image
|
- name: Build Docker Image
|
||||||
uses: docker/build-push-action@v5
|
uses: docker/build-push-action@v6
|
||||||
with:
|
with:
|
||||||
push: true
|
push: true
|
||||||
tags: ${{ steps.ev.outputs.imageTags }}
|
tags: ${{ steps.ev.outputs.imageTags }}
|
||||||
@ -151,12 +155,12 @@ jobs:
|
|||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- name: Run test suite in final docker images
|
- name: Run test suite in final docker images
|
||||||
run: |
|
run: |
|
||||||
echo "PG_PASS=$(openssl rand -base64 32)" >> .env
|
echo "PG_PASS=$(openssl rand 32 | base64 -w 0)" >> .env
|
||||||
echo "AUTHENTIK_SECRET_KEY=$(openssl rand -base64 32)" >> .env
|
echo "AUTHENTIK_SECRET_KEY=$(openssl rand 32 | base64 -w 0)" >> .env
|
||||||
docker-compose pull -q
|
docker compose pull -q
|
||||||
docker-compose up --no-start
|
docker compose up --no-start
|
||||||
docker-compose start postgresql redis
|
docker compose start postgresql redis
|
||||||
docker-compose run -u root server test-all
|
docker compose run -u root server test-all
|
||||||
sentry-release:
|
sentry-release:
|
||||||
needs:
|
needs:
|
||||||
- build-server
|
- build-server
|
||||||
@ -168,6 +172,8 @@ jobs:
|
|||||||
- name: prepare variables
|
- name: prepare variables
|
||||||
uses: ./.github/actions/docker-push-variables
|
uses: ./.github/actions/docker-push-variables
|
||||||
id: ev
|
id: ev
|
||||||
|
env:
|
||||||
|
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
||||||
with:
|
with:
|
||||||
image-name: ghcr.io/goauthentik/server
|
image-name: ghcr.io/goauthentik/server
|
||||||
- name: Get static files from docker image
|
- name: Get static files from docker image
|
||||||
|
12
.github/workflows/release-tag.yml
vendored
12
.github/workflows/release-tag.yml
vendored
@ -14,16 +14,16 @@ jobs:
|
|||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- name: Pre-release test
|
- name: Pre-release test
|
||||||
run: |
|
run: |
|
||||||
echo "PG_PASS=$(openssl rand -base64 32)" >> .env
|
echo "PG_PASS=$(openssl rand 32 | base64 -w 0)" >> .env
|
||||||
echo "AUTHENTIK_SECRET_KEY=$(openssl rand -base64 32)" >> .env
|
echo "AUTHENTIK_SECRET_KEY=$(openssl rand 32 | base64 -w 0)" >> .env
|
||||||
docker buildx install
|
docker buildx install
|
||||||
mkdir -p ./gen-ts-api
|
mkdir -p ./gen-ts-api
|
||||||
docker build -t testing:latest .
|
docker build -t testing:latest .
|
||||||
echo "AUTHENTIK_IMAGE=testing" >> .env
|
echo "AUTHENTIK_IMAGE=testing" >> .env
|
||||||
echo "AUTHENTIK_TAG=latest" >> .env
|
echo "AUTHENTIK_TAG=latest" >> .env
|
||||||
docker-compose up --no-start
|
docker compose up --no-start
|
||||||
docker-compose start postgresql redis
|
docker compose start postgresql redis
|
||||||
docker-compose run -u root server test-all
|
docker compose run -u root server test-all
|
||||||
- id: generate_token
|
- id: generate_token
|
||||||
uses: tibdex/github-app-token@v2
|
uses: tibdex/github-app-token@v2
|
||||||
with:
|
with:
|
||||||
@ -32,6 +32,8 @@ jobs:
|
|||||||
- name: prepare variables
|
- name: prepare variables
|
||||||
uses: ./.github/actions/docker-push-variables
|
uses: ./.github/actions/docker-push-variables
|
||||||
id: ev
|
id: ev
|
||||||
|
env:
|
||||||
|
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
||||||
with:
|
with:
|
||||||
image-name: ghcr.io/goauthentik/server
|
image-name: ghcr.io/goauthentik/server
|
||||||
- name: Create Release
|
- name: Create Release
|
||||||
|
2
.github/workflows/repo-stale.yml
vendored
2
.github/workflows/repo-stale.yml
vendored
@ -23,7 +23,7 @@ jobs:
|
|||||||
repo-token: ${{ steps.generate_token.outputs.token }}
|
repo-token: ${{ steps.generate_token.outputs.token }}
|
||||||
days-before-stale: 60
|
days-before-stale: 60
|
||||||
days-before-close: 7
|
days-before-close: 7
|
||||||
exempt-issue-labels: pinned,security,pr_wanted,enhancement,bug/confirmed,enhancement/confirmed,question
|
exempt-issue-labels: pinned,security,pr_wanted,enhancement,bug/confirmed,enhancement/confirmed,question,status/reviewing
|
||||||
stale-issue-label: wontfix
|
stale-issue-label: wontfix
|
||||||
stale-issue-message: >
|
stale-issue-message: >
|
||||||
This issue has been automatically marked as stale because it has not had
|
This issue has been automatically marked as stale because it has not had
|
||||||
|
15
.vscode/settings.json
vendored
15
.vscode/settings.json
vendored
@ -4,20 +4,21 @@
|
|||||||
"asgi",
|
"asgi",
|
||||||
"authentik",
|
"authentik",
|
||||||
"authn",
|
"authn",
|
||||||
|
"entra",
|
||||||
"goauthentik",
|
"goauthentik",
|
||||||
"jwks",
|
"jwks",
|
||||||
|
"kubernetes",
|
||||||
"oidc",
|
"oidc",
|
||||||
"openid",
|
"openid",
|
||||||
|
"passwordless",
|
||||||
"plex",
|
"plex",
|
||||||
"saml",
|
"saml",
|
||||||
"totp",
|
|
||||||
"webauthn",
|
|
||||||
"traefik",
|
|
||||||
"passwordless",
|
|
||||||
"kubernetes",
|
|
||||||
"sso",
|
|
||||||
"slo",
|
|
||||||
"scim",
|
"scim",
|
||||||
|
"slo",
|
||||||
|
"sso",
|
||||||
|
"totp",
|
||||||
|
"traefik",
|
||||||
|
"webauthn",
|
||||||
],
|
],
|
||||||
"todo-tree.tree.showCountsInTree": true,
|
"todo-tree.tree.showCountsInTree": true,
|
||||||
"todo-tree.tree.showBadges": true,
|
"todo-tree.tree.showBadges": true,
|
||||||
|
52
Dockerfile
52
Dockerfile
@ -1,7 +1,7 @@
|
|||||||
# syntax=docker/dockerfile:1
|
# syntax=docker/dockerfile:1
|
||||||
|
|
||||||
# Stage 1: Build website
|
# Stage 1: Build website
|
||||||
FROM --platform=${BUILDPLATFORM} docker.io/node:21 as website-builder
|
FROM --platform=${BUILDPLATFORM} docker.io/node:22 as website-builder
|
||||||
|
|
||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
|
|
||||||
@ -14,30 +14,41 @@ RUN --mount=type=bind,target=/work/website/package.json,src=./website/package.js
|
|||||||
|
|
||||||
COPY ./website /work/website/
|
COPY ./website /work/website/
|
||||||
COPY ./blueprints /work/blueprints/
|
COPY ./blueprints /work/blueprints/
|
||||||
|
COPY ./schema.yml /work/
|
||||||
COPY ./SECURITY.md /work/
|
COPY ./SECURITY.md /work/
|
||||||
|
|
||||||
RUN npm run build-docs-only
|
RUN npm run build-bundled
|
||||||
|
|
||||||
# Stage 2: Build webui
|
# Stage 2: Build webui
|
||||||
FROM --platform=${BUILDPLATFORM} docker.io/node:21 as web-builder
|
FROM --platform=${BUILDPLATFORM} docker.io/node:22 as web-builder
|
||||||
|
|
||||||
|
ARG GIT_BUILD_HASH
|
||||||
|
ENV GIT_BUILD_HASH=$GIT_BUILD_HASH
|
||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
|
|
||||||
WORKDIR /work/web
|
WORKDIR /work/web
|
||||||
|
|
||||||
RUN --mount=type=bind,target=/work/web/package.json,src=./web/package.json \
|
RUN --mount=type=bind,target=/work/web/package.json,src=./web/package.json \
|
||||||
--mount=type=bind,target=/work/web/package-lock.json,src=./web/package-lock.json \
|
--mount=type=bind,target=/work/web/package-lock.json,src=./web/package-lock.json \
|
||||||
|
--mount=type=bind,target=/work/web/sfe/package.json,src=./web/sfe/package.json \
|
||||||
|
--mount=type=bind,target=/work/web/sfe/package-lock.json,src=./web/sfe/package-lock.json \
|
||||||
|
--mount=type=bind,target=/work/web/scripts,src=./web/scripts \
|
||||||
--mount=type=cache,id=npm-web,sharing=shared,target=/root/.npm \
|
--mount=type=cache,id=npm-web,sharing=shared,target=/root/.npm \
|
||||||
|
npm ci --include=dev && \
|
||||||
|
cd sfe && \
|
||||||
npm ci --include=dev
|
npm ci --include=dev
|
||||||
|
|
||||||
|
COPY ./package.json /work
|
||||||
COPY ./web /work/web/
|
COPY ./web /work/web/
|
||||||
COPY ./website /work/website/
|
COPY ./website /work/website/
|
||||||
COPY ./gen-ts-api /work/web/node_modules/@goauthentik/api
|
COPY ./gen-ts-api /work/web/node_modules/@goauthentik/api
|
||||||
|
|
||||||
RUN npm run build
|
RUN npm run build && \
|
||||||
|
cd sfe && \
|
||||||
|
npm run build
|
||||||
|
|
||||||
# Stage 3: Build go proxy
|
# Stage 3: Build go proxy
|
||||||
FROM --platform=${BUILDPLATFORM} docker.io/golang:1.22.0-bookworm AS go-builder
|
FROM --platform=${BUILDPLATFORM} mcr.microsoft.com/oss/go/microsoft/golang:1.22-fips-bookworm AS go-builder
|
||||||
|
|
||||||
ARG TARGETOS
|
ARG TARGETOS
|
||||||
ARG TARGETARCH
|
ARG TARGETARCH
|
||||||
@ -48,6 +59,11 @@ ARG GOARCH=$TARGETARCH
|
|||||||
|
|
||||||
WORKDIR /go/src/goauthentik.io
|
WORKDIR /go/src/goauthentik.io
|
||||||
|
|
||||||
|
RUN --mount=type=cache,id=apt-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/var/cache/apt \
|
||||||
|
dpkg --add-architecture arm64 && \
|
||||||
|
apt-get update && \
|
||||||
|
apt-get install -y --no-install-recommends crossbuild-essential-arm64 gcc-aarch64-linux-gnu
|
||||||
|
|
||||||
RUN --mount=type=bind,target=/go/src/goauthentik.io/go.mod,src=./go.mod \
|
RUN --mount=type=bind,target=/go/src/goauthentik.io/go.mod,src=./go.mod \
|
||||||
--mount=type=bind,target=/go/src/goauthentik.io/go.sum,src=./go.sum \
|
--mount=type=bind,target=/go/src/goauthentik.io/go.sum,src=./go.sum \
|
||||||
--mount=type=cache,target=/go/pkg/mod \
|
--mount=type=cache,target=/go/pkg/mod \
|
||||||
@ -62,17 +78,17 @@ COPY ./internal /go/src/goauthentik.io/internal
|
|||||||
COPY ./go.mod /go/src/goauthentik.io/go.mod
|
COPY ./go.mod /go/src/goauthentik.io/go.mod
|
||||||
COPY ./go.sum /go/src/goauthentik.io/go.sum
|
COPY ./go.sum /go/src/goauthentik.io/go.sum
|
||||||
|
|
||||||
ENV CGO_ENABLED=0
|
|
||||||
|
|
||||||
RUN --mount=type=cache,sharing=locked,target=/go/pkg/mod \
|
RUN --mount=type=cache,sharing=locked,target=/go/pkg/mod \
|
||||||
--mount=type=cache,id=go-build-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/root/.cache/go-build \
|
--mount=type=cache,id=go-build-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/root/.cache/go-build \
|
||||||
GOARM="${TARGETVARIANT#v}" go build -o /go/authentik ./cmd/server
|
if [ "$TARGETARCH" = "arm64" ]; then export CC=aarch64-linux-gnu-gcc && export CC_FOR_TARGET=gcc-aarch64-linux-gnu; fi && \
|
||||||
|
CGO_ENABLED=1 GOEXPERIMENT="systemcrypto" GOFLAGS="-tags=requirefips" GOARM="${TARGETVARIANT#v}" \
|
||||||
|
go build -o /go/authentik ./cmd/server
|
||||||
|
|
||||||
# Stage 4: MaxMind GeoIP
|
# Stage 4: MaxMind GeoIP
|
||||||
FROM --platform=${BUILDPLATFORM} ghcr.io/maxmind/geoipupdate:v6.1 as geoip
|
FROM --platform=${BUILDPLATFORM} ghcr.io/maxmind/geoipupdate:v7.0.1 as geoip
|
||||||
|
|
||||||
ENV GEOIPUPDATE_EDITION_IDS="GeoLite2-City GeoLite2-ASN"
|
ENV GEOIPUPDATE_EDITION_IDS="GeoLite2-City GeoLite2-ASN"
|
||||||
ENV GEOIPUPDATE_VERBOSE="true"
|
ENV GEOIPUPDATE_VERBOSE="1"
|
||||||
ENV GEOIPUPDATE_ACCOUNT_ID_FILE="/run/secrets/GEOIPUPDATE_ACCOUNT_ID"
|
ENV GEOIPUPDATE_ACCOUNT_ID_FILE="/run/secrets/GEOIPUPDATE_ACCOUNT_ID"
|
||||||
ENV GEOIPUPDATE_LICENSE_KEY_FILE="/run/secrets/GEOIPUPDATE_LICENSE_KEY"
|
ENV GEOIPUPDATE_LICENSE_KEY_FILE="/run/secrets/GEOIPUPDATE_LICENSE_KEY"
|
||||||
|
|
||||||
@ -83,7 +99,7 @@ RUN --mount=type=secret,id=GEOIPUPDATE_ACCOUNT_ID \
|
|||||||
/bin/sh -c "/usr/bin/entry.sh || echo 'Failed to get GeoIP database, disabling'; exit 0"
|
/bin/sh -c "/usr/bin/entry.sh || echo 'Failed to get GeoIP database, disabling'; exit 0"
|
||||||
|
|
||||||
# Stage 5: Python dependencies
|
# Stage 5: Python dependencies
|
||||||
FROM docker.io/python:3.12.2-slim-bookworm AS python-deps
|
FROM ghcr.io/goauthentik/fips-python:3.12.3-slim-bookworm-fips-full AS python-deps
|
||||||
|
|
||||||
WORKDIR /ak-root/poetry
|
WORKDIR /ak-root/poetry
|
||||||
|
|
||||||
@ -96,19 +112,21 @@ RUN rm -f /etc/apt/apt.conf.d/docker-clean; echo 'Binary::apt::APT::Keep-Downloa
|
|||||||
RUN --mount=type=cache,id=apt-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/var/cache/apt \
|
RUN --mount=type=cache,id=apt-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/var/cache/apt \
|
||||||
apt-get update && \
|
apt-get update && \
|
||||||
# Required for installing pip packages
|
# Required for installing pip packages
|
||||||
apt-get install -y --no-install-recommends build-essential pkg-config libxmlsec1-dev zlib1g-dev libpq-dev
|
apt-get install -y --no-install-recommends build-essential pkg-config libpq-dev
|
||||||
|
|
||||||
RUN --mount=type=bind,target=./pyproject.toml,src=./pyproject.toml \
|
RUN --mount=type=bind,target=./pyproject.toml,src=./pyproject.toml \
|
||||||
--mount=type=bind,target=./poetry.lock,src=./poetry.lock \
|
--mount=type=bind,target=./poetry.lock,src=./poetry.lock \
|
||||||
--mount=type=cache,target=/root/.cache/pip \
|
--mount=type=cache,target=/root/.cache/pip \
|
||||||
--mount=type=cache,target=/root/.cache/pypoetry \
|
--mount=type=cache,target=/root/.cache/pypoetry \
|
||||||
python -m venv /ak-root/venv/ && \
|
python -m venv /ak-root/venv/ && \
|
||||||
|
bash -c "source ${VENV_PATH}/bin/activate && \
|
||||||
pip3 install --upgrade pip && \
|
pip3 install --upgrade pip && \
|
||||||
pip3 install poetry && \
|
pip3 install poetry && \
|
||||||
poetry install --only=main --no-ansi --no-interaction
|
poetry install --only=main --no-ansi --no-interaction --no-root && \
|
||||||
|
pip install --force-reinstall /wheels/*"
|
||||||
|
|
||||||
# Stage 6: Run
|
# Stage 6: Run
|
||||||
FROM docker.io/python:3.12.2-slim-bookworm AS final-image
|
FROM ghcr.io/goauthentik/fips-python:3.12.3-slim-bookworm-fips-full AS final-image
|
||||||
|
|
||||||
ARG GIT_BUILD_HASH
|
ARG GIT_BUILD_HASH
|
||||||
ARG VERSION
|
ARG VERSION
|
||||||
@ -125,7 +143,7 @@ WORKDIR /
|
|||||||
# We cannot cache this layer otherwise we'll end up with a bigger image
|
# We cannot cache this layer otherwise we'll end up with a bigger image
|
||||||
RUN apt-get update && \
|
RUN apt-get update && \
|
||||||
# Required for runtime
|
# Required for runtime
|
||||||
apt-get install -y --no-install-recommends libpq5 openssl libxmlsec1-openssl libmaxminddb0 ca-certificates && \
|
apt-get install -y --no-install-recommends libpq5 libmaxminddb0 ca-certificates && \
|
||||||
# Required for bootstrap & healtcheck
|
# Required for bootstrap & healtcheck
|
||||||
apt-get install -y --no-install-recommends runit && \
|
apt-get install -y --no-install-recommends runit && \
|
||||||
apt-get clean && \
|
apt-get clean && \
|
||||||
@ -149,7 +167,7 @@ COPY --from=go-builder /go/authentik /bin/authentik
|
|||||||
COPY --from=python-deps /ak-root/venv /ak-root/venv
|
COPY --from=python-deps /ak-root/venv /ak-root/venv
|
||||||
COPY --from=web-builder /work/web/dist/ /web/dist/
|
COPY --from=web-builder /work/web/dist/ /web/dist/
|
||||||
COPY --from=web-builder /work/web/authentik/ /web/authentik/
|
COPY --from=web-builder /work/web/authentik/ /web/authentik/
|
||||||
COPY --from=website-builder /work/website/help/ /website/help/
|
COPY --from=website-builder /work/website/build/ /website/help/
|
||||||
COPY --from=geoip /usr/share/GeoIP /geoip
|
COPY --from=geoip /usr/share/GeoIP /geoip
|
||||||
|
|
||||||
USER 1000
|
USER 1000
|
||||||
@ -161,6 +179,8 @@ ENV TMPDIR=/dev/shm/ \
|
|||||||
VENV_PATH="/ak-root/venv" \
|
VENV_PATH="/ak-root/venv" \
|
||||||
POETRY_VIRTUALENVS_CREATE=false
|
POETRY_VIRTUALENVS_CREATE=false
|
||||||
|
|
||||||
|
ENV GOFIPS=1
|
||||||
|
|
||||||
HEALTHCHECK --interval=30s --timeout=30s --start-period=60s --retries=3 CMD [ "ak", "healthcheck" ]
|
HEALTHCHECK --interval=30s --timeout=30s --start-period=60s --retries=3 CMD [ "ak", "healthcheck" ]
|
||||||
|
|
||||||
ENTRYPOINT [ "dumb-init", "--", "ak" ]
|
ENTRYPOINT [ "dumb-init", "--", "ak" ]
|
||||||
|
42
Makefile
42
Makefile
@ -9,6 +9,7 @@ PY_SOURCES = authentik tests scripts lifecycle .github
|
|||||||
DOCKER_IMAGE ?= "authentik:test"
|
DOCKER_IMAGE ?= "authentik:test"
|
||||||
|
|
||||||
GEN_API_TS = "gen-ts-api"
|
GEN_API_TS = "gen-ts-api"
|
||||||
|
GEN_API_PY = "gen-py-api"
|
||||||
GEN_API_GO = "gen-go-api"
|
GEN_API_GO = "gen-go-api"
|
||||||
|
|
||||||
pg_user := $(shell python -m authentik.lib.config postgresql.user 2>/dev/null)
|
pg_user := $(shell python -m authentik.lib.config postgresql.user 2>/dev/null)
|
||||||
@ -18,6 +19,7 @@ pg_name := $(shell python -m authentik.lib.config postgresql.name 2>/dev/null)
|
|||||||
CODESPELL_ARGS = -D - -D .github/codespell-dictionary.txt \
|
CODESPELL_ARGS = -D - -D .github/codespell-dictionary.txt \
|
||||||
-I .github/codespell-words.txt \
|
-I .github/codespell-words.txt \
|
||||||
-S 'web/src/locales/**' \
|
-S 'web/src/locales/**' \
|
||||||
|
-S 'website/developer-docs/api/reference/**' \
|
||||||
authentik \
|
authentik \
|
||||||
internal \
|
internal \
|
||||||
cmd \
|
cmd \
|
||||||
@ -45,12 +47,12 @@ test-go:
|
|||||||
go test -timeout 0 -v -race -cover ./...
|
go test -timeout 0 -v -race -cover ./...
|
||||||
|
|
||||||
test-docker: ## Run all tests in a docker-compose
|
test-docker: ## Run all tests in a docker-compose
|
||||||
echo "PG_PASS=$(openssl rand -base64 32)" >> .env
|
echo "PG_PASS=$(shell openssl rand 32 | base64 -w 0)" >> .env
|
||||||
echo "AUTHENTIK_SECRET_KEY=$(openssl rand -base64 32)" >> .env
|
echo "AUTHENTIK_SECRET_KEY=$(shell openssl rand 32 | base64 -w 0)" >> .env
|
||||||
docker-compose pull -q
|
docker compose pull -q
|
||||||
docker-compose up --no-start
|
docker compose up --no-start
|
||||||
docker-compose start postgresql redis
|
docker compose start postgresql redis
|
||||||
docker-compose run -u root server test-all
|
docker compose run -u root server test-all
|
||||||
rm -f .env
|
rm -f .env
|
||||||
|
|
||||||
test: ## Run the server tests and produce a coverage report (locally)
|
test: ## Run the server tests and produce a coverage report (locally)
|
||||||
@ -58,13 +60,15 @@ test: ## Run the server tests and produce a coverage report (locally)
|
|||||||
coverage html
|
coverage html
|
||||||
coverage report
|
coverage report
|
||||||
|
|
||||||
lint-fix: ## Lint and automatically fix errors in the python source code. Reports spelling errors.
|
lint-fix: lint-codespell ## Lint and automatically fix errors in the python source code. Reports spelling errors.
|
||||||
black $(PY_SOURCES)
|
black $(PY_SOURCES)
|
||||||
ruff check --fix $(PY_SOURCES)
|
ruff check --fix $(PY_SOURCES)
|
||||||
|
|
||||||
|
lint-codespell: ## Reports spelling errors.
|
||||||
codespell -w $(CODESPELL_ARGS)
|
codespell -w $(CODESPELL_ARGS)
|
||||||
|
|
||||||
lint: ## Lint the python and golang sources
|
lint: ## Lint the python and golang sources
|
||||||
bandit -r $(PY_SOURCES) -x node_modules
|
bandit -r $(PY_SOURCES) -x web/node_modules -x tests/wdio/node_modules -x website/node_modules
|
||||||
golangci-lint run -v
|
golangci-lint run -v
|
||||||
|
|
||||||
core-install:
|
core-install:
|
||||||
@ -137,7 +141,10 @@ gen-clean-ts: ## Remove generated API client for Typescript
|
|||||||
gen-clean-go: ## Remove generated API client for Go
|
gen-clean-go: ## Remove generated API client for Go
|
||||||
rm -rf ./${GEN_API_GO}/
|
rm -rf ./${GEN_API_GO}/
|
||||||
|
|
||||||
gen-clean: gen-clean-ts gen-clean-go ## Remove generated API clients
|
gen-clean-py: ## Remove generated API client for Python
|
||||||
|
rm -rf ./${GEN_API_PY}/
|
||||||
|
|
||||||
|
gen-clean: gen-clean-ts gen-clean-go gen-clean-py ## Remove generated API clients
|
||||||
|
|
||||||
gen-client-ts: gen-clean-ts ## Build and install the authentik API for Typescript into the authentik UI Application
|
gen-client-ts: gen-clean-ts ## Build and install the authentik API for Typescript into the authentik UI Application
|
||||||
docker run \
|
docker run \
|
||||||
@ -155,6 +162,20 @@ gen-client-ts: gen-clean-ts ## Build and install the authentik API for Typescri
|
|||||||
cd ./${GEN_API_TS} && npm i
|
cd ./${GEN_API_TS} && npm i
|
||||||
\cp -rf ./${GEN_API_TS}/* web/node_modules/@goauthentik/api
|
\cp -rf ./${GEN_API_TS}/* web/node_modules/@goauthentik/api
|
||||||
|
|
||||||
|
gen-client-py: gen-clean-py ## Build and install the authentik API for Python
|
||||||
|
docker run \
|
||||||
|
--rm -v ${PWD}:/local \
|
||||||
|
--user ${UID}:${GID} \
|
||||||
|
docker.io/openapitools/openapi-generator-cli:v7.4.0 generate \
|
||||||
|
-i /local/schema.yml \
|
||||||
|
-g python \
|
||||||
|
-o /local/${GEN_API_PY} \
|
||||||
|
-c /local/scripts/api-py-config.yaml \
|
||||||
|
--additional-properties=packageVersion=${NPM_VERSION} \
|
||||||
|
--git-repo-id authentik \
|
||||||
|
--git-user-id goauthentik
|
||||||
|
pip install ./${GEN_API_PY}
|
||||||
|
|
||||||
gen-client-go: gen-clean-go ## Build and install the authentik API for Golang
|
gen-client-go: gen-clean-go ## Build and install the authentik API for Golang
|
||||||
mkdir -p ./${GEN_API_GO} ./${GEN_API_GO}/templates
|
mkdir -p ./${GEN_API_GO} ./${GEN_API_GO}/templates
|
||||||
wget https://raw.githubusercontent.com/goauthentik/client-go/main/config.yaml -O ./${GEN_API_GO}/config.yaml
|
wget https://raw.githubusercontent.com/goauthentik/client-go/main/config.yaml -O ./${GEN_API_GO}/config.yaml
|
||||||
@ -220,7 +241,7 @@ website: website-lint-fix website-build ## Automatically fix formatting issues
|
|||||||
website-install:
|
website-install:
|
||||||
cd website && npm ci
|
cd website && npm ci
|
||||||
|
|
||||||
website-lint-fix:
|
website-lint-fix: lint-codespell
|
||||||
cd website && npm run prettier
|
cd website && npm run prettier
|
||||||
|
|
||||||
website-build:
|
website-build:
|
||||||
@ -234,6 +255,7 @@ website-watch: ## Build and watch the documentation website, updating automatic
|
|||||||
#########################
|
#########################
|
||||||
|
|
||||||
docker: ## Build a docker image of the current source tree
|
docker: ## Build a docker image of the current source tree
|
||||||
|
mkdir -p ${GEN_API_TS}
|
||||||
DOCKER_BUILDKIT=1 docker build . --progress plain --tag ${DOCKER_IMAGE}
|
DOCKER_BUILDKIT=1 docker build . --progress plain --tag ${DOCKER_IMAGE}
|
||||||
|
|
||||||
#########################
|
#########################
|
||||||
|
@ -25,10 +25,10 @@ For bigger setups, there is a Helm Chart [here](https://github.com/goauthentik/h
|
|||||||
|
|
||||||
## Screenshots
|
## Screenshots
|
||||||
|
|
||||||
| Light | Dark |
|
| Light | Dark |
|
||||||
| ------------------------------------------------------ | ----------------------------------------------------- |
|
| ----------------------------------------------------------- | ---------------------------------------------------------- |
|
||||||
|  |  |
|
|  |  |
|
||||||
|  |  |
|
|  |  |
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
|
20
SECURITY.md
20
SECURITY.md
@ -18,10 +18,10 @@ Even if the issue is not a CVE, we still greatly appreciate your help in hardeni
|
|||||||
|
|
||||||
(.x being the latest patch release for each version)
|
(.x being the latest patch release for each version)
|
||||||
|
|
||||||
| Version | Supported |
|
| Version | Supported |
|
||||||
| --- | --- |
|
| -------- | --------- |
|
||||||
| 2023.6.x | ✅ |
|
| 2024.4.x | ✅ |
|
||||||
| 2023.8.x | ✅ |
|
| 2024.6.x | ✅ |
|
||||||
|
|
||||||
## Reporting a Vulnerability
|
## Reporting a Vulnerability
|
||||||
|
|
||||||
@ -31,12 +31,12 @@ To report a vulnerability, send an email to [security@goauthentik.io](mailto:se
|
|||||||
|
|
||||||
authentik reserves the right to reclassify CVSS as necessary. To determine severity, we will use the CVSS calculator from NVD (https://nvd.nist.gov/vuln-metrics/cvss/v3-calculator). The calculated CVSS score will then be translated into one of the following categories:
|
authentik reserves the right to reclassify CVSS as necessary. To determine severity, we will use the CVSS calculator from NVD (https://nvd.nist.gov/vuln-metrics/cvss/v3-calculator). The calculated CVSS score will then be translated into one of the following categories:
|
||||||
|
|
||||||
| Score | Severity |
|
| Score | Severity |
|
||||||
| --- | --- |
|
| ---------- | -------- |
|
||||||
| 0.0 | None |
|
| 0.0 | None |
|
||||||
| 0.1 – 3.9 | Low |
|
| 0.1 – 3.9 | Low |
|
||||||
| 4.0 – 6.9 | Medium |
|
| 4.0 – 6.9 | Medium |
|
||||||
| 7.0 – 8.9 | High |
|
| 7.0 – 8.9 | High |
|
||||||
| 9.0 – 10.0 | Critical |
|
| 9.0 – 10.0 | Critical |
|
||||||
|
|
||||||
## Disclosure process
|
## Disclosure process
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
from os import environ
|
from os import environ
|
||||||
|
|
||||||
__version__ = "2024.2.1"
|
__version__ = "2024.6.1"
|
||||||
ENV_GIT_HASH_KEY = "GIT_BUILD_HASH"
|
ENV_GIT_HASH_KEY = "GIT_BUILD_HASH"
|
||||||
|
|
||||||
|
|
||||||
|
@ -2,18 +2,21 @@
|
|||||||
|
|
||||||
import platform
|
import platform
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
from ssl import OPENSSL_VERSION
|
||||||
from sys import version as python_version
|
from sys import version as python_version
|
||||||
from typing import TypedDict
|
from typing import TypedDict
|
||||||
|
|
||||||
|
from cryptography.hazmat.backends.openssl.backend import backend
|
||||||
from django.utils.timezone import now
|
from django.utils.timezone import now
|
||||||
from drf_spectacular.utils import extend_schema
|
from drf_spectacular.utils import extend_schema
|
||||||
from gunicorn import version_info as gunicorn_version
|
|
||||||
from rest_framework.fields import SerializerMethodField
|
from rest_framework.fields import SerializerMethodField
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.views import APIView
|
from rest_framework.views import APIView
|
||||||
|
|
||||||
|
from authentik import get_full_version
|
||||||
from authentik.core.api.utils import PassiveSerializer
|
from authentik.core.api.utils import PassiveSerializer
|
||||||
|
from authentik.enterprise.license import LicenseKey
|
||||||
from authentik.lib.config import CONFIG
|
from authentik.lib.config import CONFIG
|
||||||
from authentik.lib.utils.reflection import get_env
|
from authentik.lib.utils.reflection import get_env
|
||||||
from authentik.outposts.apps import MANAGED_OUTPOST
|
from authentik.outposts.apps import MANAGED_OUTPOST
|
||||||
@ -25,11 +28,13 @@ class RuntimeDict(TypedDict):
|
|||||||
"""Runtime information"""
|
"""Runtime information"""
|
||||||
|
|
||||||
python_version: str
|
python_version: str
|
||||||
gunicorn_version: str
|
|
||||||
environment: str
|
environment: str
|
||||||
architecture: str
|
architecture: str
|
||||||
platform: str
|
platform: str
|
||||||
uname: str
|
uname: str
|
||||||
|
openssl_version: str
|
||||||
|
openssl_fips_enabled: bool | None
|
||||||
|
authentik_version: str
|
||||||
|
|
||||||
|
|
||||||
class SystemInfoSerializer(PassiveSerializer):
|
class SystemInfoSerializer(PassiveSerializer):
|
||||||
@ -64,11 +69,15 @@ class SystemInfoSerializer(PassiveSerializer):
|
|||||||
def get_runtime(self, request: Request) -> RuntimeDict:
|
def get_runtime(self, request: Request) -> RuntimeDict:
|
||||||
"""Get versions"""
|
"""Get versions"""
|
||||||
return {
|
return {
|
||||||
"python_version": python_version,
|
|
||||||
"gunicorn_version": ".".join(str(x) for x in gunicorn_version),
|
|
||||||
"environment": get_env(),
|
|
||||||
"architecture": platform.machine(),
|
"architecture": platform.machine(),
|
||||||
|
"authentik_version": get_full_version(),
|
||||||
|
"environment": get_env(),
|
||||||
|
"openssl_fips_enabled": (
|
||||||
|
backend._fips_enabled if LicenseKey.get_total().is_valid() else None
|
||||||
|
),
|
||||||
|
"openssl_version": OPENSSL_VERSION,
|
||||||
"platform": platform.platform(),
|
"platform": platform.platform(),
|
||||||
|
"python_version": python_version,
|
||||||
"uname": " ".join(platform.uname()),
|
"uname": " ".join(platform.uname()),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -10,7 +10,7 @@ from rest_framework.response import Response
|
|||||||
from rest_framework.views import APIView
|
from rest_framework.views import APIView
|
||||||
|
|
||||||
from authentik import __version__, get_build_hash
|
from authentik import __version__, get_build_hash
|
||||||
from authentik.admin.tasks import VERSION_CACHE_KEY, update_latest_version
|
from authentik.admin.tasks import VERSION_CACHE_KEY, VERSION_NULL, update_latest_version
|
||||||
from authentik.core.api.utils import PassiveSerializer
|
from authentik.core.api.utils import PassiveSerializer
|
||||||
|
|
||||||
|
|
||||||
@ -19,6 +19,7 @@ class VersionSerializer(PassiveSerializer):
|
|||||||
|
|
||||||
version_current = SerializerMethodField()
|
version_current = SerializerMethodField()
|
||||||
version_latest = SerializerMethodField()
|
version_latest = SerializerMethodField()
|
||||||
|
version_latest_valid = SerializerMethodField()
|
||||||
build_hash = SerializerMethodField()
|
build_hash = SerializerMethodField()
|
||||||
outdated = SerializerMethodField()
|
outdated = SerializerMethodField()
|
||||||
|
|
||||||
@ -38,6 +39,10 @@ class VersionSerializer(PassiveSerializer):
|
|||||||
return __version__
|
return __version__
|
||||||
return version_in_cache
|
return version_in_cache
|
||||||
|
|
||||||
|
def get_version_latest_valid(self, _) -> bool:
|
||||||
|
"""Check if latest version is valid"""
|
||||||
|
return cache.get(VERSION_CACHE_KEY) != VERSION_NULL
|
||||||
|
|
||||||
def get_outdated(self, instance) -> bool:
|
def get_outdated(self, instance) -> bool:
|
||||||
"""Check if we're running the latest version"""
|
"""Check if we're running the latest version"""
|
||||||
return parse(self.get_version_current(instance)) < parse(self.get_version_latest(instance))
|
return parse(self.get_version_current(instance)) < parse(self.get_version_latest(instance))
|
||||||
|
@ -18,6 +18,7 @@ from authentik.lib.utils.http import get_http_session
|
|||||||
from authentik.root.celery import CELERY_APP
|
from authentik.root.celery import CELERY_APP
|
||||||
|
|
||||||
LOGGER = get_logger()
|
LOGGER = get_logger()
|
||||||
|
VERSION_NULL = "0.0.0"
|
||||||
VERSION_CACHE_KEY = "authentik_latest_version"
|
VERSION_CACHE_KEY = "authentik_latest_version"
|
||||||
VERSION_CACHE_TIMEOUT = 8 * 60 * 60 # 8 hours
|
VERSION_CACHE_TIMEOUT = 8 * 60 * 60 # 8 hours
|
||||||
# Chop of the first ^ because we want to search the entire string
|
# Chop of the first ^ because we want to search the entire string
|
||||||
@ -55,7 +56,7 @@ def clear_update_notifications():
|
|||||||
def update_latest_version(self: SystemTask):
|
def update_latest_version(self: SystemTask):
|
||||||
"""Update latest version info"""
|
"""Update latest version info"""
|
||||||
if CONFIG.get_bool("disable_update_check"):
|
if CONFIG.get_bool("disable_update_check"):
|
||||||
cache.set(VERSION_CACHE_KEY, "0.0.0", VERSION_CACHE_TIMEOUT)
|
cache.set(VERSION_CACHE_KEY, VERSION_NULL, VERSION_CACHE_TIMEOUT)
|
||||||
self.set_status(TaskStatus.WARNING, "Version check disabled.")
|
self.set_status(TaskStatus.WARNING, "Version check disabled.")
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
@ -82,7 +83,7 @@ def update_latest_version(self: SystemTask):
|
|||||||
event_dict["message"] = f"Changelog: {match.group()}"
|
event_dict["message"] = f"Changelog: {match.group()}"
|
||||||
Event.new(EventAction.UPDATE_AVAILABLE, **event_dict).save()
|
Event.new(EventAction.UPDATE_AVAILABLE, **event_dict).save()
|
||||||
except (RequestException, IndexError) as exc:
|
except (RequestException, IndexError) as exc:
|
||||||
cache.set(VERSION_CACHE_KEY, "0.0.0", VERSION_CACHE_TIMEOUT)
|
cache.set(VERSION_CACHE_KEY, VERSION_NULL, VERSION_CACHE_TIMEOUT)
|
||||||
self.set_error(exc)
|
self.set_error(exc)
|
||||||
|
|
||||||
|
|
||||||
|
@ -10,26 +10,3 @@ class AuthentikAPIConfig(AppConfig):
|
|||||||
label = "authentik_api"
|
label = "authentik_api"
|
||||||
mountpoint = "api/"
|
mountpoint = "api/"
|
||||||
verbose_name = "authentik API"
|
verbose_name = "authentik API"
|
||||||
|
|
||||||
def ready(self) -> None:
|
|
||||||
from drf_spectacular.extensions import OpenApiAuthenticationExtension
|
|
||||||
|
|
||||||
from authentik.api.authentication import TokenAuthentication
|
|
||||||
|
|
||||||
# Class is defined here as it needs to be created early enough that drf-spectacular will
|
|
||||||
# find it, but also won't cause any import issues
|
|
||||||
|
|
||||||
class TokenSchema(OpenApiAuthenticationExtension):
|
|
||||||
"""Auth schema"""
|
|
||||||
|
|
||||||
target_class = TokenAuthentication
|
|
||||||
name = "authentik"
|
|
||||||
|
|
||||||
def get_security_definition(self, auto_schema):
|
|
||||||
"""Auth schema"""
|
|
||||||
return {
|
|
||||||
"type": "apiKey",
|
|
||||||
"in": "header",
|
|
||||||
"name": "Authorization",
|
|
||||||
"scheme": "bearer",
|
|
||||||
}
|
|
||||||
|
@ -4,6 +4,7 @@ from hmac import compare_digest
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
|
from drf_spectacular.extensions import OpenApiAuthenticationExtension
|
||||||
from rest_framework.authentication import BaseAuthentication, get_authorization_header
|
from rest_framework.authentication import BaseAuthentication, get_authorization_header
|
||||||
from rest_framework.exceptions import AuthenticationFailed
|
from rest_framework.exceptions import AuthenticationFailed
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
@ -102,3 +103,14 @@ class TokenAuthentication(BaseAuthentication):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
return (user, None) # pragma: no cover
|
return (user, None) # pragma: no cover
|
||||||
|
|
||||||
|
|
||||||
|
class TokenSchema(OpenApiAuthenticationExtension):
|
||||||
|
"""Auth schema"""
|
||||||
|
|
||||||
|
target_class = TokenAuthentication
|
||||||
|
name = "authentik"
|
||||||
|
|
||||||
|
def get_security_definition(self, auto_schema):
|
||||||
|
"""Auth schema"""
|
||||||
|
return {"type": "http", "scheme": "bearer"}
|
||||||
|
@ -12,6 +12,7 @@ from drf_spectacular.settings import spectacular_settings
|
|||||||
from drf_spectacular.types import OpenApiTypes
|
from drf_spectacular.types import OpenApiTypes
|
||||||
from rest_framework.settings import api_settings
|
from rest_framework.settings import api_settings
|
||||||
|
|
||||||
|
from authentik.api.apps import AuthentikAPIConfig
|
||||||
from authentik.api.pagination import PAGINATION_COMPONENT_NAME, PAGINATION_SCHEMA
|
from authentik.api.pagination import PAGINATION_COMPONENT_NAME, PAGINATION_SCHEMA
|
||||||
|
|
||||||
|
|
||||||
@ -101,3 +102,12 @@ def postprocess_schema_responses(result, generator: SchemaGenerator, **kwargs):
|
|||||||
comp = result["components"]["schemas"][component]
|
comp = result["components"]["schemas"][component]
|
||||||
comp["additionalProperties"] = {}
|
comp["additionalProperties"] = {}
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def preprocess_schema_exclude_non_api(endpoints, **kwargs):
|
||||||
|
"""Filter out all API Views which are not mounted under /api"""
|
||||||
|
return [
|
||||||
|
(path, path_regex, method, callback)
|
||||||
|
for path, path_regex, method, callback in endpoints
|
||||||
|
if path.startswith("/" + AuthentikAPIConfig.mountpoint)
|
||||||
|
]
|
||||||
|
@ -1,13 +1,13 @@
|
|||||||
{% extends "base/skeleton.html" %}
|
{% extends "base/skeleton.html" %}
|
||||||
|
|
||||||
{% load static %}
|
{% load authentik_core %}
|
||||||
|
|
||||||
{% block title %}
|
{% block title %}
|
||||||
API Browser - {{ brand.branding_title }}
|
API Browser - {{ brand.branding_title }}
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block head %}
|
{% block head %}
|
||||||
<script src="{% static 'dist/standalone/api-browser/index.js' %}?version={{ version }}" type="module"></script>
|
{% versioned_script "dist/standalone/api-browser/index-%v.js" %}
|
||||||
<meta name="theme-color" content="#151515" media="(prefers-color-scheme: light)">
|
<meta name="theme-color" content="#151515" media="(prefers-color-scheme: light)">
|
||||||
<meta name="theme-color" content="#151515" media="(prefers-color-scheme: dark)">
|
<meta name="theme-color" content="#151515" media="(prefers-color-scheme: dark)">
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
@ -68,7 +68,11 @@ class ConfigView(APIView):
|
|||||||
"""Get all capabilities this server instance supports"""
|
"""Get all capabilities this server instance supports"""
|
||||||
caps = []
|
caps = []
|
||||||
deb_test = settings.DEBUG or settings.TEST
|
deb_test = settings.DEBUG or settings.TEST
|
||||||
if Path(settings.MEDIA_ROOT).is_mount() or deb_test:
|
if (
|
||||||
|
CONFIG.get("storage.media.backend", "file") == "s3"
|
||||||
|
or Path(settings.STORAGES["default"]["OPTIONS"]["location"]).is_mount()
|
||||||
|
or deb_test
|
||||||
|
):
|
||||||
caps.append(Capabilities.CAN_SAVE_MEDIA)
|
caps.append(Capabilities.CAN_SAVE_MEDIA)
|
||||||
for processor in get_context_processors():
|
for processor in get_context_processors():
|
||||||
if cap := processor.capability():
|
if cap := processor.capability():
|
||||||
|
@ -8,6 +8,8 @@ from django.apps import AppConfig
|
|||||||
from django.db import DatabaseError, InternalError, ProgrammingError
|
from django.db import DatabaseError, InternalError, ProgrammingError
|
||||||
from structlog.stdlib import BoundLogger, get_logger
|
from structlog.stdlib import BoundLogger, get_logger
|
||||||
|
|
||||||
|
from authentik.root.signals import startup
|
||||||
|
|
||||||
|
|
||||||
class ManagedAppConfig(AppConfig):
|
class ManagedAppConfig(AppConfig):
|
||||||
"""Basic reconciliation logic for apps"""
|
"""Basic reconciliation logic for apps"""
|
||||||
@ -23,9 +25,12 @@ class ManagedAppConfig(AppConfig):
|
|||||||
|
|
||||||
def ready(self) -> None:
|
def ready(self) -> None:
|
||||||
self.import_related()
|
self.import_related()
|
||||||
|
startup.connect(self._on_startup_callback, dispatch_uid=self.label)
|
||||||
|
return super().ready()
|
||||||
|
|
||||||
|
def _on_startup_callback(self, sender, **_):
|
||||||
self._reconcile_global()
|
self._reconcile_global()
|
||||||
self._reconcile_tenant()
|
self._reconcile_tenant()
|
||||||
return super().ready()
|
|
||||||
|
|
||||||
def import_related(self):
|
def import_related(self):
|
||||||
"""Automatically import related modules which rely on just being imported
|
"""Automatically import related modules which rely on just being imported
|
||||||
|
@ -4,12 +4,14 @@ from json import dumps
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from django.core.management.base import BaseCommand, no_translations
|
from django.core.management.base import BaseCommand, no_translations
|
||||||
from django.db.models import Model
|
from django.db.models import Model, fields
|
||||||
from drf_jsonschema_serializer.convert import field_to_converter
|
from drf_jsonschema_serializer.convert import converter, field_to_converter
|
||||||
from rest_framework.fields import Field, JSONField, UUIDField
|
from rest_framework.fields import Field, JSONField, UUIDField
|
||||||
|
from rest_framework.relations import PrimaryKeyRelatedField
|
||||||
from rest_framework.serializers import Serializer
|
from rest_framework.serializers import Serializer
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
|
from authentik import __version__
|
||||||
from authentik.blueprints.v1.common import BlueprintEntryDesiredState
|
from authentik.blueprints.v1.common import BlueprintEntryDesiredState
|
||||||
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT, is_model_allowed
|
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT, is_model_allowed
|
||||||
from authentik.blueprints.v1.meta.registry import BaseMetaModel, registry
|
from authentik.blueprints.v1.meta.registry import BaseMetaModel, registry
|
||||||
@ -18,6 +20,23 @@ from authentik.lib.models import SerializerModel
|
|||||||
LOGGER = get_logger()
|
LOGGER = get_logger()
|
||||||
|
|
||||||
|
|
||||||
|
@converter
|
||||||
|
class PrimaryKeyRelatedFieldConverter:
|
||||||
|
"""Custom primary key field converter which is aware of non-integer based PKs
|
||||||
|
|
||||||
|
This is not an exhaustive fix for other non-int PKs, however in authentik we either
|
||||||
|
use UUIDs or ints"""
|
||||||
|
|
||||||
|
field_class = PrimaryKeyRelatedField
|
||||||
|
|
||||||
|
def convert(self, field: PrimaryKeyRelatedField):
|
||||||
|
model: Model = field.queryset.model
|
||||||
|
pk_field = model._meta.pk
|
||||||
|
if isinstance(pk_field, fields.UUIDField):
|
||||||
|
return {"type": "string", "format": "uuid"}
|
||||||
|
return {"type": "integer"}
|
||||||
|
|
||||||
|
|
||||||
class Command(BaseCommand):
|
class Command(BaseCommand):
|
||||||
"""Generate JSON Schema for blueprints"""
|
"""Generate JSON Schema for blueprints"""
|
||||||
|
|
||||||
@ -29,7 +48,7 @@ class Command(BaseCommand):
|
|||||||
"$schema": "http://json-schema.org/draft-07/schema",
|
"$schema": "http://json-schema.org/draft-07/schema",
|
||||||
"$id": "https://goauthentik.io/blueprints/schema.json",
|
"$id": "https://goauthentik.io/blueprints/schema.json",
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"title": "authentik Blueprint schema",
|
"title": f"authentik {__version__} Blueprint schema",
|
||||||
"required": ["version", "entries"],
|
"required": ["version", "entries"],
|
||||||
"properties": {
|
"properties": {
|
||||||
"version": {
|
"version": {
|
||||||
|
@ -39,7 +39,7 @@ def reconcile_app(app_name: str):
|
|||||||
def wrapper(*args, **kwargs):
|
def wrapper(*args, **kwargs):
|
||||||
config = apps.get_app_config(app_name)
|
config = apps.get_app_config(app_name)
|
||||||
if isinstance(config, ManagedAppConfig):
|
if isinstance(config, ManagedAppConfig):
|
||||||
config.ready()
|
config._on_startup_callback(None)
|
||||||
return func(*args, **kwargs)
|
return func(*args, **kwargs)
|
||||||
|
|
||||||
return wrapper
|
return wrapper
|
||||||
|
@ -75,7 +75,7 @@ class BlueprintEntry:
|
|||||||
_state: BlueprintEntryState = field(default_factory=BlueprintEntryState)
|
_state: BlueprintEntryState = field(default_factory=BlueprintEntryState)
|
||||||
|
|
||||||
def __post_init__(self, *args, **kwargs) -> None:
|
def __post_init__(self, *args, **kwargs) -> None:
|
||||||
self.__tag_contexts: list["YAMLTagContext"] = []
|
self.__tag_contexts: list[YAMLTagContext] = []
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def from_model(model: SerializerModel, *extra_identifier_names: str) -> "BlueprintEntry":
|
def from_model(model: SerializerModel, *extra_identifier_names: str) -> "BlueprintEntry":
|
||||||
@ -556,7 +556,11 @@ class BlueprintDumper(SafeDumper):
|
|||||||
|
|
||||||
def factory(items):
|
def factory(items):
|
||||||
final_dict = dict(items)
|
final_dict = dict(items)
|
||||||
|
# Remove internal state variables
|
||||||
final_dict.pop("_state", None)
|
final_dict.pop("_state", None)
|
||||||
|
# Future-proof to only remove the ID if we don't set a value
|
||||||
|
if "id" in final_dict and final_dict.get("id") is None:
|
||||||
|
final_dict.pop("id")
|
||||||
return final_dict
|
return final_dict
|
||||||
|
|
||||||
data = asdict(data, dict_factory=factory)
|
data = asdict(data, dict_factory=factory)
|
||||||
|
@ -19,8 +19,6 @@ from guardian.models import UserObjectPermission
|
|||||||
from rest_framework.exceptions import ValidationError
|
from rest_framework.exceptions import ValidationError
|
||||||
from rest_framework.serializers import BaseSerializer, Serializer
|
from rest_framework.serializers import BaseSerializer, Serializer
|
||||||
from structlog.stdlib import BoundLogger, get_logger
|
from structlog.stdlib import BoundLogger, get_logger
|
||||||
from structlog.testing import capture_logs
|
|
||||||
from structlog.types import EventDict
|
|
||||||
from yaml import load
|
from yaml import load
|
||||||
|
|
||||||
from authentik.blueprints.v1.common import (
|
from authentik.blueprints.v1.common import (
|
||||||
@ -41,7 +39,16 @@ from authentik.core.models import (
|
|||||||
)
|
)
|
||||||
from authentik.enterprise.license import LicenseKey
|
from authentik.enterprise.license import LicenseKey
|
||||||
from authentik.enterprise.models import LicenseUsage
|
from authentik.enterprise.models import LicenseUsage
|
||||||
|
from authentik.enterprise.providers.google_workspace.models import (
|
||||||
|
GoogleWorkspaceProviderGroup,
|
||||||
|
GoogleWorkspaceProviderUser,
|
||||||
|
)
|
||||||
|
from authentik.enterprise.providers.microsoft_entra.models import (
|
||||||
|
MicrosoftEntraProviderGroup,
|
||||||
|
MicrosoftEntraProviderUser,
|
||||||
|
)
|
||||||
from authentik.enterprise.providers.rac.models import ConnectionToken
|
from authentik.enterprise.providers.rac.models import ConnectionToken
|
||||||
|
from authentik.events.logs import LogEvent, capture_logs
|
||||||
from authentik.events.models import SystemTask
|
from authentik.events.models import SystemTask
|
||||||
from authentik.events.utils import cleanse_dict
|
from authentik.events.utils import cleanse_dict
|
||||||
from authentik.flows.models import FlowToken, Stage
|
from authentik.flows.models import FlowToken, Stage
|
||||||
@ -51,7 +58,9 @@ from authentik.outposts.models import OutpostServiceConnection
|
|||||||
from authentik.policies.models import Policy, PolicyBindingModel
|
from authentik.policies.models import Policy, PolicyBindingModel
|
||||||
from authentik.policies.reputation.models import Reputation
|
from authentik.policies.reputation.models import Reputation
|
||||||
from authentik.providers.oauth2.models import AccessToken, AuthorizationCode, RefreshToken
|
from authentik.providers.oauth2.models import AccessToken, AuthorizationCode, RefreshToken
|
||||||
from authentik.providers.scim.models import SCIMGroup, SCIMUser
|
from authentik.providers.scim.models import SCIMProviderGroup, SCIMProviderUser
|
||||||
|
from authentik.sources.scim.models import SCIMSourceGroup, SCIMSourceUser
|
||||||
|
from authentik.stages.authenticator_webauthn.models import WebAuthnDeviceType
|
||||||
from authentik.tenants.models import Tenant
|
from authentik.tenants.models import Tenant
|
||||||
|
|
||||||
# Context set when the serializer is created in a blueprint context
|
# Context set when the serializer is created in a blueprint context
|
||||||
@ -85,10 +94,11 @@ def excluded_models() -> list[type[Model]]:
|
|||||||
# Classes that have other dependencies
|
# Classes that have other dependencies
|
||||||
AuthenticatedSession,
|
AuthenticatedSession,
|
||||||
# Classes which are only internally managed
|
# Classes which are only internally managed
|
||||||
|
# FIXME: these shouldn't need to be explicitly listed, but rather based off of a mixin
|
||||||
FlowToken,
|
FlowToken,
|
||||||
LicenseUsage,
|
LicenseUsage,
|
||||||
SCIMGroup,
|
SCIMProviderGroup,
|
||||||
SCIMUser,
|
SCIMProviderUser,
|
||||||
Tenant,
|
Tenant,
|
||||||
SystemTask,
|
SystemTask,
|
||||||
ConnectionToken,
|
ConnectionToken,
|
||||||
@ -96,6 +106,13 @@ def excluded_models() -> list[type[Model]]:
|
|||||||
AccessToken,
|
AccessToken,
|
||||||
RefreshToken,
|
RefreshToken,
|
||||||
Reputation,
|
Reputation,
|
||||||
|
WebAuthnDeviceType,
|
||||||
|
SCIMSourceUser,
|
||||||
|
SCIMSourceGroup,
|
||||||
|
GoogleWorkspaceProviderUser,
|
||||||
|
GoogleWorkspaceProviderGroup,
|
||||||
|
MicrosoftEntraProviderUser,
|
||||||
|
MicrosoftEntraProviderGroup,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@ -161,7 +178,7 @@ class Importer:
|
|||||||
|
|
||||||
def updater(value) -> Any:
|
def updater(value) -> Any:
|
||||||
if value in self.__pk_map:
|
if value in self.__pk_map:
|
||||||
self.logger.debug("updating reference in entry", value=value)
|
self.logger.debug("Updating reference in entry", value=value)
|
||||||
return self.__pk_map[value]
|
return self.__pk_map[value]
|
||||||
return value
|
return value
|
||||||
|
|
||||||
@ -250,7 +267,7 @@ class Importer:
|
|||||||
model_instance = existing_models.first()
|
model_instance = existing_models.first()
|
||||||
if not isinstance(model(), BaseMetaModel) and model_instance:
|
if not isinstance(model(), BaseMetaModel) and model_instance:
|
||||||
self.logger.debug(
|
self.logger.debug(
|
||||||
"initialise serializer with instance",
|
"Initialise serializer with instance",
|
||||||
model=model,
|
model=model,
|
||||||
instance=model_instance,
|
instance=model_instance,
|
||||||
pk=model_instance.pk,
|
pk=model_instance.pk,
|
||||||
@ -260,14 +277,14 @@ class Importer:
|
|||||||
elif model_instance and entry.state == BlueprintEntryDesiredState.MUST_CREATED:
|
elif model_instance and entry.state == BlueprintEntryDesiredState.MUST_CREATED:
|
||||||
raise EntryInvalidError.from_entry(
|
raise EntryInvalidError.from_entry(
|
||||||
(
|
(
|
||||||
f"state is set to {BlueprintEntryDesiredState.MUST_CREATED} "
|
f"State is set to {BlueprintEntryDesiredState.MUST_CREATED} "
|
||||||
"and object exists already",
|
"and object exists already",
|
||||||
),
|
),
|
||||||
entry,
|
entry,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
self.logger.debug(
|
self.logger.debug(
|
||||||
"initialised new serializer instance",
|
"Initialised new serializer instance",
|
||||||
model=model,
|
model=model,
|
||||||
**cleanse_dict(updated_identifiers),
|
**cleanse_dict(updated_identifiers),
|
||||||
)
|
)
|
||||||
@ -324,7 +341,7 @@ class Importer:
|
|||||||
model: type[SerializerModel] = registry.get_model(model_app_label, model_name)
|
model: type[SerializerModel] = registry.get_model(model_app_label, model_name)
|
||||||
except LookupError:
|
except LookupError:
|
||||||
self.logger.warning(
|
self.logger.warning(
|
||||||
"app or model does not exist", app=model_app_label, model=model_name
|
"App or Model does not exist", app=model_app_label, model=model_name
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
# Validate each single entry
|
# Validate each single entry
|
||||||
@ -336,7 +353,7 @@ class Importer:
|
|||||||
if entry.get_state(self._import) == BlueprintEntryDesiredState.ABSENT:
|
if entry.get_state(self._import) == BlueprintEntryDesiredState.ABSENT:
|
||||||
serializer = exc.serializer
|
serializer = exc.serializer
|
||||||
else:
|
else:
|
||||||
self.logger.warning(f"entry invalid: {exc}", entry=entry, error=exc)
|
self.logger.warning(f"Entry invalid: {exc}", entry=entry, error=exc)
|
||||||
if raise_errors:
|
if raise_errors:
|
||||||
raise exc
|
raise exc
|
||||||
return False
|
return False
|
||||||
@ -356,14 +373,14 @@ class Importer:
|
|||||||
and state == BlueprintEntryDesiredState.CREATED
|
and state == BlueprintEntryDesiredState.CREATED
|
||||||
):
|
):
|
||||||
self.logger.debug(
|
self.logger.debug(
|
||||||
"instance exists, skipping",
|
"Instance exists, skipping",
|
||||||
model=model,
|
model=model,
|
||||||
instance=instance,
|
instance=instance,
|
||||||
pk=instance.pk,
|
pk=instance.pk,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
instance = serializer.save()
|
instance = serializer.save()
|
||||||
self.logger.debug("updated model", model=instance)
|
self.logger.debug("Updated model", model=instance)
|
||||||
if "pk" in entry.identifiers:
|
if "pk" in entry.identifiers:
|
||||||
self.__pk_map[entry.identifiers["pk"]] = instance.pk
|
self.__pk_map[entry.identifiers["pk"]] = instance.pk
|
||||||
entry._state = BlueprintEntryState(instance)
|
entry._state = BlueprintEntryState(instance)
|
||||||
@ -371,12 +388,12 @@ class Importer:
|
|||||||
instance: Model | None = serializer.instance
|
instance: Model | None = serializer.instance
|
||||||
if instance.pk:
|
if instance.pk:
|
||||||
instance.delete()
|
instance.delete()
|
||||||
self.logger.debug("deleted model", mode=instance)
|
self.logger.debug("Deleted model", mode=instance)
|
||||||
continue
|
continue
|
||||||
self.logger.debug("entry to delete with no instance, skipping")
|
self.logger.debug("Entry to delete with no instance, skipping")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def validate(self, raise_validation_errors=False) -> tuple[bool, list[EventDict]]:
|
def validate(self, raise_validation_errors=False) -> tuple[bool, list[LogEvent]]:
|
||||||
"""Validate loaded blueprint export, ensure all models are allowed
|
"""Validate loaded blueprint export, ensure all models are allowed
|
||||||
and serializers have no errors"""
|
and serializers have no errors"""
|
||||||
self.logger.debug("Starting blueprint import validation")
|
self.logger.debug("Starting blueprint import validation")
|
||||||
@ -390,9 +407,7 @@ class Importer:
|
|||||||
):
|
):
|
||||||
successful = self._apply_models(raise_errors=raise_validation_errors)
|
successful = self._apply_models(raise_errors=raise_validation_errors)
|
||||||
if not successful:
|
if not successful:
|
||||||
self.logger.debug("Blueprint validation failed")
|
self.logger.warning("Blueprint validation failed")
|
||||||
for log in logs:
|
|
||||||
getattr(self.logger, log.get("log_level"))(**log)
|
|
||||||
self.logger.debug("Finished blueprint import validation")
|
self.logger.debug("Finished blueprint import validation")
|
||||||
self._import = orig_import
|
self._import = orig_import
|
||||||
return successful, logs
|
return successful, logs
|
||||||
|
@ -30,6 +30,7 @@ from authentik.blueprints.v1.common import BlueprintLoader, BlueprintMetadata, E
|
|||||||
from authentik.blueprints.v1.importer import Importer
|
from authentik.blueprints.v1.importer import Importer
|
||||||
from authentik.blueprints.v1.labels import LABEL_AUTHENTIK_INSTANTIATE
|
from authentik.blueprints.v1.labels import LABEL_AUTHENTIK_INSTANTIATE
|
||||||
from authentik.blueprints.v1.oci import OCI_PREFIX
|
from authentik.blueprints.v1.oci import OCI_PREFIX
|
||||||
|
from authentik.events.logs import capture_logs
|
||||||
from authentik.events.models import TaskStatus
|
from authentik.events.models import TaskStatus
|
||||||
from authentik.events.system_tasks import SystemTask, prefill_task
|
from authentik.events.system_tasks import SystemTask, prefill_task
|
||||||
from authentik.events.utils import sanitize_dict
|
from authentik.events.utils import sanitize_dict
|
||||||
@ -211,14 +212,15 @@ def apply_blueprint(self: SystemTask, instance_pk: str):
|
|||||||
if not valid:
|
if not valid:
|
||||||
instance.status = BlueprintInstanceStatus.ERROR
|
instance.status = BlueprintInstanceStatus.ERROR
|
||||||
instance.save()
|
instance.save()
|
||||||
self.set_status(TaskStatus.ERROR, *[x["event"] for x in logs])
|
self.set_status(TaskStatus.ERROR, *logs)
|
||||||
return
|
|
||||||
applied = importer.apply()
|
|
||||||
if not applied:
|
|
||||||
instance.status = BlueprintInstanceStatus.ERROR
|
|
||||||
instance.save()
|
|
||||||
self.set_status(TaskStatus.ERROR, "Failed to apply")
|
|
||||||
return
|
return
|
||||||
|
with capture_logs() as logs:
|
||||||
|
applied = importer.apply()
|
||||||
|
if not applied:
|
||||||
|
instance.status = BlueprintInstanceStatus.ERROR
|
||||||
|
instance.save()
|
||||||
|
self.set_status(TaskStatus.ERROR, *logs)
|
||||||
|
return
|
||||||
instance.status = BlueprintInstanceStatus.SUCCESSFUL
|
instance.status = BlueprintInstanceStatus.SUCCESSFUL
|
||||||
instance.last_applied_hash = file_hash
|
instance.last_applied_hash = file_hash
|
||||||
instance.last_applied = now()
|
instance.last_applied = now()
|
||||||
|
@ -11,21 +11,20 @@ from rest_framework.filters import OrderingFilter, SearchFilter
|
|||||||
from rest_framework.permissions import AllowAny
|
from rest_framework.permissions import AllowAny
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.serializers import ModelSerializer
|
|
||||||
from rest_framework.validators import UniqueValidator
|
from rest_framework.validators import UniqueValidator
|
||||||
from rest_framework.viewsets import ModelViewSet
|
from rest_framework.viewsets import ModelViewSet
|
||||||
|
|
||||||
from authentik.api.authorization import SecretKeyFilter
|
from authentik.api.authorization import SecretKeyFilter
|
||||||
from authentik.brands.models import Brand
|
from authentik.brands.models import Brand
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.utils import PassiveSerializer
|
from authentik.core.api.utils import ModelSerializer, PassiveSerializer
|
||||||
from authentik.tenants.utils import get_current_tenant
|
from authentik.tenants.utils import get_current_tenant
|
||||||
|
|
||||||
|
|
||||||
class FooterLinkSerializer(PassiveSerializer):
|
class FooterLinkSerializer(PassiveSerializer):
|
||||||
"""Links returned in Config API"""
|
"""Links returned in Config API"""
|
||||||
|
|
||||||
href = CharField(read_only=True)
|
href = CharField(read_only=True, allow_null=True)
|
||||||
name = CharField(read_only=True)
|
name = CharField(read_only=True)
|
||||||
|
|
||||||
|
|
||||||
|
@ -0,0 +1,21 @@
|
|||||||
|
# Generated by Django 5.0.4 on 2024-04-18 18:56
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
("authentik_brands", "0005_tenantuuid_to_branduuid"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="brand",
|
||||||
|
index=models.Index(fields=["domain"], name="authentik_b_domain_b9b24a_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="brand",
|
||||||
|
index=models.Index(fields=["default"], name="authentik_b_default_3ccf12_idx"),
|
||||||
|
),
|
||||||
|
]
|
@ -84,3 +84,7 @@ class Brand(SerializerModel):
|
|||||||
class Meta:
|
class Meta:
|
||||||
verbose_name = _("Brand")
|
verbose_name = _("Brand")
|
||||||
verbose_name_plural = _("Brands")
|
verbose_name_plural = _("Brands")
|
||||||
|
indexes = [
|
||||||
|
models.Index(fields=["domain"]),
|
||||||
|
models.Index(fields=["default"]),
|
||||||
|
]
|
||||||
|
@ -17,18 +17,18 @@ from rest_framework.fields import CharField, ReadOnlyField, SerializerMethodFiel
|
|||||||
from rest_framework.parsers import MultiPartParser
|
from rest_framework.parsers import MultiPartParser
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.serializers import ModelSerializer
|
|
||||||
from rest_framework.viewsets import ModelViewSet
|
from rest_framework.viewsets import ModelViewSet
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
from structlog.testing import capture_logs
|
|
||||||
|
|
||||||
from authentik.admin.api.metrics import CoordinateSerializer
|
from authentik.admin.api.metrics import CoordinateSerializer
|
||||||
|
from authentik.api.pagination import Pagination
|
||||||
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT
|
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT
|
||||||
from authentik.core.api.providers import ProviderSerializer
|
from authentik.core.api.providers import ProviderSerializer
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
|
from authentik.core.api.utils import ModelSerializer
|
||||||
from authentik.core.models import Application, User
|
from authentik.core.models import Application, User
|
||||||
|
from authentik.events.logs import LogEventSerializer, capture_logs
|
||||||
from authentik.events.models import EventAction
|
from authentik.events.models import EventAction
|
||||||
from authentik.events.utils import sanitize_dict
|
|
||||||
from authentik.lib.utils.file import (
|
from authentik.lib.utils.file import (
|
||||||
FilePathSerializer,
|
FilePathSerializer,
|
||||||
FileUploadSerializer,
|
FileUploadSerializer,
|
||||||
@ -37,16 +37,19 @@ from authentik.lib.utils.file import (
|
|||||||
)
|
)
|
||||||
from authentik.policies.api.exec import PolicyTestResultSerializer
|
from authentik.policies.api.exec import PolicyTestResultSerializer
|
||||||
from authentik.policies.engine import PolicyEngine
|
from authentik.policies.engine import PolicyEngine
|
||||||
from authentik.policies.types import PolicyResult
|
from authentik.policies.types import CACHE_PREFIX, PolicyResult
|
||||||
from authentik.rbac.decorators import permission_required
|
from authentik.rbac.decorators import permission_required
|
||||||
from authentik.rbac.filters import ObjectFilter
|
from authentik.rbac.filters import ObjectFilter
|
||||||
|
|
||||||
LOGGER = get_logger()
|
LOGGER = get_logger()
|
||||||
|
|
||||||
|
|
||||||
def user_app_cache_key(user_pk: str) -> str:
|
def user_app_cache_key(user_pk: str, page_number: int | None = None) -> str:
|
||||||
"""Cache key where application list for user is saved"""
|
"""Cache key where application list for user is saved"""
|
||||||
return f"goauthentik.io/core/app_access/{user_pk}"
|
key = f"{CACHE_PREFIX}/app_access/{user_pk}"
|
||||||
|
if page_number:
|
||||||
|
key += f"/{page_number}"
|
||||||
|
return key
|
||||||
|
|
||||||
|
|
||||||
class ApplicationSerializer(ModelSerializer):
|
class ApplicationSerializer(ModelSerializer):
|
||||||
@ -100,7 +103,7 @@ class ApplicationSerializer(ModelSerializer):
|
|||||||
class ApplicationViewSet(UsedByMixin, ModelViewSet):
|
class ApplicationViewSet(UsedByMixin, ModelViewSet):
|
||||||
"""Application Viewset"""
|
"""Application Viewset"""
|
||||||
|
|
||||||
queryset = Application.objects.all().prefetch_related("provider")
|
queryset = Application.objects.all().prefetch_related("provider").prefetch_related("policies")
|
||||||
serializer_class = ApplicationSerializer
|
serializer_class = ApplicationSerializer
|
||||||
search_fields = [
|
search_fields = [
|
||||||
"name",
|
"name",
|
||||||
@ -182,9 +185,9 @@ class ApplicationViewSet(UsedByMixin, ModelViewSet):
|
|||||||
if request.user.is_superuser:
|
if request.user.is_superuser:
|
||||||
log_messages = []
|
log_messages = []
|
||||||
for log in logs:
|
for log in logs:
|
||||||
if log.get("process", "") == "PolicyProcess":
|
if log.attributes.get("process", "") == "PolicyProcess":
|
||||||
continue
|
continue
|
||||||
log_messages.append(sanitize_dict(log))
|
log_messages.append(LogEventSerializer(log).data)
|
||||||
result.log_messages = log_messages
|
result.log_messages = log_messages
|
||||||
response = PolicyTestResultSerializer(result)
|
response = PolicyTestResultSerializer(result)
|
||||||
return Response(response.data)
|
return Response(response.data)
|
||||||
@ -214,7 +217,8 @@ class ApplicationViewSet(UsedByMixin, ModelViewSet):
|
|||||||
return super().list(request)
|
return super().list(request)
|
||||||
|
|
||||||
queryset = self._filter_queryset_for_list(self.get_queryset())
|
queryset = self._filter_queryset_for_list(self.get_queryset())
|
||||||
pagined_apps = self.paginate_queryset(queryset)
|
paginator: Pagination = self.paginator
|
||||||
|
paginated_apps = paginator.paginate_queryset(queryset, request)
|
||||||
|
|
||||||
if "for_user" in request.query_params:
|
if "for_user" in request.query_params:
|
||||||
try:
|
try:
|
||||||
@ -228,20 +232,22 @@ class ApplicationViewSet(UsedByMixin, ModelViewSet):
|
|||||||
raise ValidationError({"for_user": "User not found"})
|
raise ValidationError({"for_user": "User not found"})
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise ValidationError from exc
|
raise ValidationError from exc
|
||||||
allowed_applications = self._get_allowed_applications(pagined_apps, user=for_user)
|
allowed_applications = self._get_allowed_applications(paginated_apps, user=for_user)
|
||||||
serializer = self.get_serializer(allowed_applications, many=True)
|
serializer = self.get_serializer(allowed_applications, many=True)
|
||||||
return self.get_paginated_response(serializer.data)
|
return self.get_paginated_response(serializer.data)
|
||||||
|
|
||||||
allowed_applications = []
|
allowed_applications = []
|
||||||
if not should_cache:
|
if not should_cache:
|
||||||
allowed_applications = self._get_allowed_applications(pagined_apps)
|
allowed_applications = self._get_allowed_applications(paginated_apps)
|
||||||
if should_cache:
|
if should_cache:
|
||||||
allowed_applications = cache.get(user_app_cache_key(self.request.user.pk))
|
allowed_applications = cache.get(
|
||||||
|
user_app_cache_key(self.request.user.pk, paginator.page.number)
|
||||||
|
)
|
||||||
if not allowed_applications:
|
if not allowed_applications:
|
||||||
LOGGER.debug("Caching allowed application list")
|
LOGGER.debug("Caching allowed application list", page=paginator.page.number)
|
||||||
allowed_applications = self._get_allowed_applications(pagined_apps)
|
allowed_applications = self._get_allowed_applications(paginated_apps)
|
||||||
cache.set(
|
cache.set(
|
||||||
user_app_cache_key(self.request.user.pk),
|
user_app_cache_key(self.request.user.pk, paginator.page.number),
|
||||||
allowed_applications,
|
allowed_applications,
|
||||||
timeout=86400,
|
timeout=86400,
|
||||||
)
|
)
|
||||||
|
@ -8,12 +8,12 @@ from rest_framework import mixins
|
|||||||
from rest_framework.fields import SerializerMethodField
|
from rest_framework.fields import SerializerMethodField
|
||||||
from rest_framework.filters import OrderingFilter, SearchFilter
|
from rest_framework.filters import OrderingFilter, SearchFilter
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
from rest_framework.serializers import ModelSerializer
|
|
||||||
from rest_framework.viewsets import GenericViewSet
|
from rest_framework.viewsets import GenericViewSet
|
||||||
from ua_parser import user_agent_parser
|
from ua_parser import user_agent_parser
|
||||||
|
|
||||||
from authentik.api.authorization import OwnerSuperuserPermissions
|
from authentik.api.authorization import OwnerSuperuserPermissions
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
|
from authentik.core.api.utils import ModelSerializer
|
||||||
from authentik.core.models import AuthenticatedSession
|
from authentik.core.models import AuthenticatedSession
|
||||||
from authentik.events.context_processors.asn import ASN_CONTEXT_PROCESSOR, ASNDict
|
from authentik.events.context_processors.asn import ASN_CONTEXT_PROCESSOR, ASNDict
|
||||||
from authentik.events.context_processors.geoip import GEOIP_CONTEXT_PROCESSOR, GeoIPDict
|
from authentik.events.context_processors.geoip import GEOIP_CONTEXT_PROCESSOR, GeoIPDict
|
||||||
|
@ -2,20 +2,27 @@
|
|||||||
|
|
||||||
from json import loads
|
from json import loads
|
||||||
|
|
||||||
|
from django.db.models import Prefetch
|
||||||
from django.http import Http404
|
from django.http import Http404
|
||||||
from django_filters.filters import CharFilter, ModelMultipleChoiceFilter
|
from django_filters.filters import CharFilter, ModelMultipleChoiceFilter
|
||||||
from django_filters.filterset import FilterSet
|
from django_filters.filterset import FilterSet
|
||||||
from drf_spectacular.utils import OpenApiResponse, extend_schema
|
from drf_spectacular.utils import (
|
||||||
|
OpenApiParameter,
|
||||||
|
OpenApiResponse,
|
||||||
|
extend_schema,
|
||||||
|
extend_schema_field,
|
||||||
|
)
|
||||||
from guardian.shortcuts import get_objects_for_user
|
from guardian.shortcuts import get_objects_for_user
|
||||||
from rest_framework.decorators import action
|
from rest_framework.decorators import action
|
||||||
from rest_framework.fields import CharField, IntegerField
|
from rest_framework.fields import CharField, IntegerField, SerializerMethodField
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.serializers import ListSerializer, ModelSerializer, ValidationError
|
from rest_framework.serializers import ListSerializer, ValidationError
|
||||||
|
from rest_framework.validators import UniqueValidator
|
||||||
from rest_framework.viewsets import ModelViewSet
|
from rest_framework.viewsets import ModelViewSet
|
||||||
|
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.utils import JSONDictField, PassiveSerializer
|
from authentik.core.api.utils import JSONDictField, ModelSerializer, PassiveSerializer
|
||||||
from authentik.core.models import Group, User
|
from authentik.core.models import Group, User
|
||||||
from authentik.rbac.api.roles import RoleSerializer
|
from authentik.rbac.api.roles import RoleSerializer
|
||||||
from authentik.rbac.decorators import permission_required
|
from authentik.rbac.decorators import permission_required
|
||||||
@ -45,9 +52,7 @@ class GroupSerializer(ModelSerializer):
|
|||||||
"""Group Serializer"""
|
"""Group Serializer"""
|
||||||
|
|
||||||
attributes = JSONDictField(required=False)
|
attributes = JSONDictField(required=False)
|
||||||
users_obj = ListSerializer(
|
users_obj = SerializerMethodField(allow_null=True)
|
||||||
child=GroupMemberSerializer(), read_only=True, source="users", required=False
|
|
||||||
)
|
|
||||||
roles_obj = ListSerializer(
|
roles_obj = ListSerializer(
|
||||||
child=RoleSerializer(),
|
child=RoleSerializer(),
|
||||||
read_only=True,
|
read_only=True,
|
||||||
@ -58,6 +63,19 @@ class GroupSerializer(ModelSerializer):
|
|||||||
|
|
||||||
num_pk = IntegerField(read_only=True)
|
num_pk = IntegerField(read_only=True)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def _should_include_users(self) -> bool:
|
||||||
|
request: Request = self.context.get("request", None)
|
||||||
|
if not request:
|
||||||
|
return True
|
||||||
|
return str(request.query_params.get("include_users", "true")).lower() == "true"
|
||||||
|
|
||||||
|
@extend_schema_field(GroupMemberSerializer(many=True))
|
||||||
|
def get_users_obj(self, instance: Group) -> list[GroupMemberSerializer] | None:
|
||||||
|
if not self._should_include_users:
|
||||||
|
return None
|
||||||
|
return GroupMemberSerializer(instance.users, many=True).data
|
||||||
|
|
||||||
def validate_parent(self, parent: Group | None):
|
def validate_parent(self, parent: Group | None):
|
||||||
"""Validate group parent (if set), ensuring the parent isn't itself"""
|
"""Validate group parent (if set), ensuring the parent isn't itself"""
|
||||||
if not self.instance or not parent:
|
if not self.instance or not parent:
|
||||||
@ -84,7 +102,10 @@ class GroupSerializer(ModelSerializer):
|
|||||||
extra_kwargs = {
|
extra_kwargs = {
|
||||||
"users": {
|
"users": {
|
||||||
"default": list,
|
"default": list,
|
||||||
}
|
},
|
||||||
|
# TODO: This field isn't unique on the database which is hard to backport
|
||||||
|
# hence we just validate the uniqueness here
|
||||||
|
"name": {"validators": [UniqueValidator(Group.objects.all())]},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -130,22 +151,49 @@ class GroupFilter(FilterSet):
|
|||||||
fields = ["name", "is_superuser", "members_by_pk", "attributes", "members_by_username"]
|
fields = ["name", "is_superuser", "members_by_pk", "attributes", "members_by_username"]
|
||||||
|
|
||||||
|
|
||||||
class UserAccountSerializer(PassiveSerializer):
|
|
||||||
"""Account adding/removing operations"""
|
|
||||||
|
|
||||||
pk = IntegerField(required=True)
|
|
||||||
|
|
||||||
|
|
||||||
class GroupViewSet(UsedByMixin, ModelViewSet):
|
class GroupViewSet(UsedByMixin, ModelViewSet):
|
||||||
"""Group Viewset"""
|
"""Group Viewset"""
|
||||||
|
|
||||||
queryset = Group.objects.all().select_related("parent").prefetch_related("users")
|
class UserAccountSerializer(PassiveSerializer):
|
||||||
|
"""Account adding/removing operations"""
|
||||||
|
|
||||||
|
pk = IntegerField(required=True)
|
||||||
|
|
||||||
|
queryset = Group.objects.none()
|
||||||
serializer_class = GroupSerializer
|
serializer_class = GroupSerializer
|
||||||
search_fields = ["name", "is_superuser"]
|
search_fields = ["name", "is_superuser"]
|
||||||
filterset_class = GroupFilter
|
filterset_class = GroupFilter
|
||||||
ordering = ["name"]
|
ordering = ["name"]
|
||||||
|
|
||||||
@permission_required(None, ["authentik_core.add_user"])
|
def get_queryset(self):
|
||||||
|
base_qs = Group.objects.all().select_related("parent").prefetch_related("roles")
|
||||||
|
|
||||||
|
if self.serializer_class(context={"request": self.request})._should_include_users:
|
||||||
|
base_qs = base_qs.prefetch_related("users")
|
||||||
|
else:
|
||||||
|
base_qs = base_qs.prefetch_related(
|
||||||
|
Prefetch("users", queryset=User.objects.all().only("id"))
|
||||||
|
)
|
||||||
|
|
||||||
|
return base_qs
|
||||||
|
|
||||||
|
@extend_schema(
|
||||||
|
parameters=[
|
||||||
|
OpenApiParameter("include_users", bool, default=True),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
def list(self, request, *args, **kwargs):
|
||||||
|
return super().list(request, *args, **kwargs)
|
||||||
|
|
||||||
|
@extend_schema(
|
||||||
|
parameters=[
|
||||||
|
OpenApiParameter("include_users", bool, default=True),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
def retrieve(self, request, *args, **kwargs):
|
||||||
|
return super().retrieve(request, *args, **kwargs)
|
||||||
|
|
||||||
|
@permission_required("authentik_core.add_user_to_group")
|
||||||
@extend_schema(
|
@extend_schema(
|
||||||
request=UserAccountSerializer,
|
request=UserAccountSerializer,
|
||||||
responses={
|
responses={
|
||||||
@ -153,7 +201,13 @@ class GroupViewSet(UsedByMixin, ModelViewSet):
|
|||||||
404: OpenApiResponse(description="User not found"),
|
404: OpenApiResponse(description="User not found"),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@action(detail=True, methods=["POST"], pagination_class=None, filter_backends=[])
|
@action(
|
||||||
|
detail=True,
|
||||||
|
methods=["POST"],
|
||||||
|
pagination_class=None,
|
||||||
|
filter_backends=[],
|
||||||
|
permission_classes=[],
|
||||||
|
)
|
||||||
def add_user(self, request: Request, pk: str) -> Response:
|
def add_user(self, request: Request, pk: str) -> Response:
|
||||||
"""Add user to group"""
|
"""Add user to group"""
|
||||||
group: Group = self.get_object()
|
group: Group = self.get_object()
|
||||||
@ -169,7 +223,7 @@ class GroupViewSet(UsedByMixin, ModelViewSet):
|
|||||||
group.users.add(user)
|
group.users.add(user)
|
||||||
return Response(status=204)
|
return Response(status=204)
|
||||||
|
|
||||||
@permission_required(None, ["authentik_core.add_user"])
|
@permission_required("authentik_core.remove_user_from_group")
|
||||||
@extend_schema(
|
@extend_schema(
|
||||||
request=UserAccountSerializer,
|
request=UserAccountSerializer,
|
||||||
responses={
|
responses={
|
||||||
@ -177,7 +231,13 @@ class GroupViewSet(UsedByMixin, ModelViewSet):
|
|||||||
404: OpenApiResponse(description="User not found"),
|
404: OpenApiResponse(description="User not found"),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@action(detail=True, methods=["POST"], pagination_class=None, filter_backends=[])
|
@action(
|
||||||
|
detail=True,
|
||||||
|
methods=["POST"],
|
||||||
|
pagination_class=None,
|
||||||
|
filter_backends=[],
|
||||||
|
permission_classes=[],
|
||||||
|
)
|
||||||
def remove_user(self, request: Request, pk: str) -> Response:
|
def remove_user(self, request: Request, pk: str) -> Response:
|
||||||
"""Add user to group"""
|
"""Add user to group"""
|
||||||
group: Group = self.get_object()
|
group: Group = self.get_object()
|
||||||
|
79
authentik/core/api/object_types.py
Normal file
79
authentik/core/api/object_types.py
Normal file
@ -0,0 +1,79 @@
|
|||||||
|
"""API Utilities"""
|
||||||
|
|
||||||
|
from drf_spectacular.utils import extend_schema
|
||||||
|
from rest_framework.decorators import action
|
||||||
|
from rest_framework.fields import (
|
||||||
|
BooleanField,
|
||||||
|
CharField,
|
||||||
|
)
|
||||||
|
from rest_framework.request import Request
|
||||||
|
from rest_framework.response import Response
|
||||||
|
|
||||||
|
from authentik.core.api.utils import PassiveSerializer
|
||||||
|
from authentik.enterprise.apps import EnterpriseConfig
|
||||||
|
from authentik.lib.utils.reflection import all_subclasses
|
||||||
|
|
||||||
|
|
||||||
|
class TypeCreateSerializer(PassiveSerializer):
|
||||||
|
"""Types of an object that can be created"""
|
||||||
|
|
||||||
|
name = CharField(required=True)
|
||||||
|
description = CharField(required=True)
|
||||||
|
component = CharField(required=True)
|
||||||
|
model_name = CharField(required=True)
|
||||||
|
|
||||||
|
icon_url = CharField(required=False)
|
||||||
|
requires_enterprise = BooleanField(default=False)
|
||||||
|
|
||||||
|
|
||||||
|
class CreatableType:
|
||||||
|
"""Class to inherit from to mark a model as creatable, even if the model itself is marked
|
||||||
|
as abstract"""
|
||||||
|
|
||||||
|
|
||||||
|
class NonCreatableType:
|
||||||
|
"""Class to inherit from to mark a model as non-creatable even if it is not abstract"""
|
||||||
|
|
||||||
|
|
||||||
|
class TypesMixin:
|
||||||
|
"""Mixin which adds an API endpoint to list all possible types that can be created"""
|
||||||
|
|
||||||
|
@extend_schema(responses={200: TypeCreateSerializer(many=True)})
|
||||||
|
@action(detail=False, pagination_class=None, filter_backends=[])
|
||||||
|
def types(self, request: Request, additional: list[dict] | None = None) -> Response:
|
||||||
|
"""Get all creatable types"""
|
||||||
|
data = []
|
||||||
|
for subclass in all_subclasses(self.queryset.model):
|
||||||
|
instance = None
|
||||||
|
if subclass._meta.abstract:
|
||||||
|
if not issubclass(subclass, CreatableType):
|
||||||
|
continue
|
||||||
|
# Circumvent the django protection for not being able to instantiate
|
||||||
|
# abstract models. We need a model instance to access .component
|
||||||
|
# and further down .icon_url
|
||||||
|
instance = subclass.__new__(subclass)
|
||||||
|
# Django re-sets abstract = False so we need to override that
|
||||||
|
instance.Meta.abstract = True
|
||||||
|
else:
|
||||||
|
if issubclass(subclass, NonCreatableType):
|
||||||
|
continue
|
||||||
|
instance = subclass()
|
||||||
|
try:
|
||||||
|
data.append(
|
||||||
|
{
|
||||||
|
"name": subclass._meta.verbose_name,
|
||||||
|
"description": subclass.__doc__,
|
||||||
|
"component": instance.component,
|
||||||
|
"model_name": subclass._meta.model_name,
|
||||||
|
"icon_url": getattr(instance, "icon_url", None),
|
||||||
|
"requires_enterprise": isinstance(
|
||||||
|
subclass._meta.app_config, EnterpriseConfig
|
||||||
|
),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
except NotImplementedError:
|
||||||
|
continue
|
||||||
|
if additional:
|
||||||
|
data.extend(additional)
|
||||||
|
data = sorted(data, key=lambda x: x["name"])
|
||||||
|
return Response(TypeCreateSerializer(data, many=True).data)
|
@ -8,19 +8,23 @@ from guardian.shortcuts import get_objects_for_user
|
|||||||
from rest_framework import mixins
|
from rest_framework import mixins
|
||||||
from rest_framework.decorators import action
|
from rest_framework.decorators import action
|
||||||
from rest_framework.exceptions import PermissionDenied
|
from rest_framework.exceptions import PermissionDenied
|
||||||
from rest_framework.fields import BooleanField, CharField
|
from rest_framework.fields import BooleanField, CharField, SerializerMethodField
|
||||||
|
from rest_framework.relations import PrimaryKeyRelatedField
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.serializers import ModelSerializer, SerializerMethodField
|
|
||||||
from rest_framework.viewsets import GenericViewSet
|
from rest_framework.viewsets import GenericViewSet
|
||||||
|
|
||||||
from authentik.blueprints.api import ManagedSerializer
|
from authentik.blueprints.api import ManagedSerializer
|
||||||
|
from authentik.core.api.object_types import TypesMixin
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.utils import MetaNameSerializer, PassiveSerializer, TypeCreateSerializer
|
from authentik.core.api.utils import (
|
||||||
|
MetaNameSerializer,
|
||||||
|
ModelSerializer,
|
||||||
|
PassiveSerializer,
|
||||||
|
)
|
||||||
from authentik.core.expression.evaluator import PropertyMappingEvaluator
|
from authentik.core.expression.evaluator import PropertyMappingEvaluator
|
||||||
from authentik.core.models import PropertyMapping
|
from authentik.core.models import Group, PropertyMapping, User
|
||||||
from authentik.events.utils import sanitize_item
|
from authentik.events.utils import sanitize_item
|
||||||
from authentik.lib.utils.reflection import all_subclasses
|
|
||||||
from authentik.policies.api.exec import PolicyTestSerializer
|
from authentik.policies.api.exec import PolicyTestSerializer
|
||||||
from authentik.rbac.decorators import permission_required
|
from authentik.rbac.decorators import permission_required
|
||||||
|
|
||||||
@ -64,6 +68,7 @@ class PropertyMappingSerializer(ManagedSerializer, ModelSerializer, MetaNameSeri
|
|||||||
|
|
||||||
|
|
||||||
class PropertyMappingViewSet(
|
class PropertyMappingViewSet(
|
||||||
|
TypesMixin,
|
||||||
mixins.RetrieveModelMixin,
|
mixins.RetrieveModelMixin,
|
||||||
mixins.DestroyModelMixin,
|
mixins.DestroyModelMixin,
|
||||||
UsedByMixin,
|
UsedByMixin,
|
||||||
@ -72,7 +77,15 @@ class PropertyMappingViewSet(
|
|||||||
):
|
):
|
||||||
"""PropertyMapping Viewset"""
|
"""PropertyMapping Viewset"""
|
||||||
|
|
||||||
queryset = PropertyMapping.objects.none()
|
class PropertyMappingTestSerializer(PolicyTestSerializer):
|
||||||
|
"""Test property mapping execution for a user/group with context"""
|
||||||
|
|
||||||
|
user = PrimaryKeyRelatedField(queryset=User.objects.all(), required=False, allow_null=True)
|
||||||
|
group = PrimaryKeyRelatedField(
|
||||||
|
queryset=Group.objects.all(), required=False, allow_null=True
|
||||||
|
)
|
||||||
|
|
||||||
|
queryset = PropertyMapping.objects.select_subclasses()
|
||||||
serializer_class = PropertyMappingSerializer
|
serializer_class = PropertyMappingSerializer
|
||||||
search_fields = [
|
search_fields = [
|
||||||
"name",
|
"name",
|
||||||
@ -80,29 +93,9 @@ class PropertyMappingViewSet(
|
|||||||
filterset_fields = {"managed": ["isnull"]}
|
filterset_fields = {"managed": ["isnull"]}
|
||||||
ordering = ["name"]
|
ordering = ["name"]
|
||||||
|
|
||||||
def get_queryset(self): # pragma: no cover
|
|
||||||
return PropertyMapping.objects.select_subclasses()
|
|
||||||
|
|
||||||
@extend_schema(responses={200: TypeCreateSerializer(many=True)})
|
|
||||||
@action(detail=False, pagination_class=None, filter_backends=[])
|
|
||||||
def types(self, request: Request) -> Response:
|
|
||||||
"""Get all creatable property-mapping types"""
|
|
||||||
data = []
|
|
||||||
for subclass in all_subclasses(self.queryset.model):
|
|
||||||
subclass: PropertyMapping
|
|
||||||
data.append(
|
|
||||||
{
|
|
||||||
"name": subclass._meta.verbose_name,
|
|
||||||
"description": subclass.__doc__,
|
|
||||||
"component": subclass().component,
|
|
||||||
"model_name": subclass._meta.model_name,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
return Response(TypeCreateSerializer(data, many=True).data)
|
|
||||||
|
|
||||||
@permission_required("authentik_core.view_propertymapping")
|
@permission_required("authentik_core.view_propertymapping")
|
||||||
@extend_schema(
|
@extend_schema(
|
||||||
request=PolicyTestSerializer(),
|
request=PropertyMappingTestSerializer(),
|
||||||
responses={
|
responses={
|
||||||
200: PropertyMappingTestResultSerializer,
|
200: PropertyMappingTestResultSerializer,
|
||||||
400: OpenApiResponse(description="Invalid parameters"),
|
400: OpenApiResponse(description="Invalid parameters"),
|
||||||
@ -120,29 +113,39 @@ class PropertyMappingViewSet(
|
|||||||
"""Test Property Mapping"""
|
"""Test Property Mapping"""
|
||||||
_mapping: PropertyMapping = self.get_object()
|
_mapping: PropertyMapping = self.get_object()
|
||||||
# Use `get_subclass` to get correct class and correct `.evaluate` implementation
|
# Use `get_subclass` to get correct class and correct `.evaluate` implementation
|
||||||
mapping = PropertyMapping.objects.get_subclass(pk=_mapping.pk)
|
mapping: PropertyMapping = PropertyMapping.objects.get_subclass(pk=_mapping.pk)
|
||||||
# FIXME: when we separate policy mappings between ones for sources
|
# FIXME: when we separate policy mappings between ones for sources
|
||||||
# and ones for providers, we need to make the user field optional for the source mapping
|
# and ones for providers, we need to make the user field optional for the source mapping
|
||||||
test_params = PolicyTestSerializer(data=request.data)
|
test_params = self.PropertyMappingTestSerializer(data=request.data)
|
||||||
if not test_params.is_valid():
|
if not test_params.is_valid():
|
||||||
return Response(test_params.errors, status=400)
|
return Response(test_params.errors, status=400)
|
||||||
|
|
||||||
format_result = str(request.GET.get("format_result", "false")).lower() == "true"
|
format_result = str(request.GET.get("format_result", "false")).lower() == "true"
|
||||||
|
|
||||||
# User permission check, only allow mapping testing for users that are readable
|
context: dict = test_params.validated_data.get("context", {})
|
||||||
users = get_objects_for_user(request.user, "authentik_core.view_user").filter(
|
context.setdefault("user", None)
|
||||||
pk=test_params.validated_data["user"].pk
|
|
||||||
)
|
if user := test_params.validated_data.get("user"):
|
||||||
if not users.exists():
|
# User permission check, only allow mapping testing for users that are readable
|
||||||
raise PermissionDenied()
|
users = get_objects_for_user(request.user, "authentik_core.view_user").filter(
|
||||||
|
pk=user.pk
|
||||||
|
)
|
||||||
|
if not users.exists():
|
||||||
|
raise PermissionDenied()
|
||||||
|
context["user"] = user
|
||||||
|
if group := test_params.validated_data.get("group"):
|
||||||
|
# Group permission check, only allow mapping testing for groups that are readable
|
||||||
|
groups = get_objects_for_user(request.user, "authentik_core.view_group").filter(
|
||||||
|
pk=group.pk
|
||||||
|
)
|
||||||
|
if not groups.exists():
|
||||||
|
raise PermissionDenied()
|
||||||
|
context["group"] = group
|
||||||
|
context["request"] = self.request
|
||||||
|
|
||||||
response_data = {"successful": True, "result": ""}
|
response_data = {"successful": True, "result": ""}
|
||||||
try:
|
try:
|
||||||
result = mapping.evaluate(
|
result = mapping.evaluate(**context)
|
||||||
users.first(),
|
|
||||||
self.request,
|
|
||||||
**test_params.validated_data.get("context", {}),
|
|
||||||
)
|
|
||||||
response_data["result"] = dumps(
|
response_data["result"] = dumps(
|
||||||
sanitize_item(result), indent=(4 if format_result else None)
|
sanitize_item(result), indent=(4 if format_result else None)
|
||||||
)
|
)
|
@ -5,20 +5,14 @@ from django.db.models.query import Q
|
|||||||
from django.utils.translation import gettext_lazy as _
|
from django.utils.translation import gettext_lazy as _
|
||||||
from django_filters.filters import BooleanFilter
|
from django_filters.filters import BooleanFilter
|
||||||
from django_filters.filterset import FilterSet
|
from django_filters.filterset import FilterSet
|
||||||
from drf_spectacular.utils import extend_schema
|
|
||||||
from rest_framework import mixins
|
from rest_framework import mixins
|
||||||
from rest_framework.decorators import action
|
from rest_framework.fields import ReadOnlyField, SerializerMethodField
|
||||||
from rest_framework.fields import ReadOnlyField
|
|
||||||
from rest_framework.request import Request
|
|
||||||
from rest_framework.response import Response
|
|
||||||
from rest_framework.serializers import ModelSerializer, SerializerMethodField
|
|
||||||
from rest_framework.viewsets import GenericViewSet
|
from rest_framework.viewsets import GenericViewSet
|
||||||
|
|
||||||
|
from authentik.core.api.object_types import TypesMixin
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.utils import MetaNameSerializer, TypeCreateSerializer
|
from authentik.core.api.utils import MetaNameSerializer, ModelSerializer
|
||||||
from authentik.core.models import Provider
|
from authentik.core.models import Provider
|
||||||
from authentik.enterprise.apps import EnterpriseConfig
|
|
||||||
from authentik.lib.utils.reflection import all_subclasses
|
|
||||||
|
|
||||||
|
|
||||||
class ProviderSerializer(ModelSerializer, MetaNameSerializer):
|
class ProviderSerializer(ModelSerializer, MetaNameSerializer):
|
||||||
@ -63,8 +57,12 @@ class ProviderFilter(FilterSet):
|
|||||||
"""Filter for providers"""
|
"""Filter for providers"""
|
||||||
|
|
||||||
application__isnull = BooleanFilter(method="filter_application__isnull")
|
application__isnull = BooleanFilter(method="filter_application__isnull")
|
||||||
backchannel_only = BooleanFilter(
|
backchannel = BooleanFilter(
|
||||||
method="filter_backchannel_only",
|
method="filter_backchannel",
|
||||||
|
label=_(
|
||||||
|
"When not set all providers are returned. When set to true, only backchannel "
|
||||||
|
"providers are returned. When set to false, backchannel providers are excluded"
|
||||||
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
def filter_application__isnull(self, queryset: QuerySet, name, value):
|
def filter_application__isnull(self, queryset: QuerySet, name, value):
|
||||||
@ -75,12 +73,14 @@ class ProviderFilter(FilterSet):
|
|||||||
| Q(application__isnull=value)
|
| Q(application__isnull=value)
|
||||||
)
|
)
|
||||||
|
|
||||||
def filter_backchannel_only(self, queryset: QuerySet, name, value):
|
def filter_backchannel(self, queryset: QuerySet, name, value):
|
||||||
"""Only return backchannel providers"""
|
"""By default all providers are returned. When set to true, only backchannel providers are
|
||||||
|
returned. When set to false, backchannel providers are excluded"""
|
||||||
return queryset.filter(is_backchannel=value)
|
return queryset.filter(is_backchannel=value)
|
||||||
|
|
||||||
|
|
||||||
class ProviderViewSet(
|
class ProviderViewSet(
|
||||||
|
TypesMixin,
|
||||||
mixins.RetrieveModelMixin,
|
mixins.RetrieveModelMixin,
|
||||||
mixins.DestroyModelMixin,
|
mixins.DestroyModelMixin,
|
||||||
UsedByMixin,
|
UsedByMixin,
|
||||||
@ -99,31 +99,3 @@ class ProviderViewSet(
|
|||||||
|
|
||||||
def get_queryset(self): # pragma: no cover
|
def get_queryset(self): # pragma: no cover
|
||||||
return Provider.objects.select_subclasses()
|
return Provider.objects.select_subclasses()
|
||||||
|
|
||||||
@extend_schema(responses={200: TypeCreateSerializer(many=True)})
|
|
||||||
@action(detail=False, pagination_class=None, filter_backends=[])
|
|
||||||
def types(self, request: Request) -> Response:
|
|
||||||
"""Get all creatable provider types"""
|
|
||||||
data = []
|
|
||||||
for subclass in all_subclasses(self.queryset.model):
|
|
||||||
subclass: Provider
|
|
||||||
if subclass._meta.abstract:
|
|
||||||
continue
|
|
||||||
data.append(
|
|
||||||
{
|
|
||||||
"name": subclass._meta.verbose_name,
|
|
||||||
"description": subclass.__doc__,
|
|
||||||
"component": subclass().component,
|
|
||||||
"model_name": subclass._meta.model_name,
|
|
||||||
"requires_enterprise": isinstance(subclass._meta.app_config, EnterpriseConfig),
|
|
||||||
}
|
|
||||||
)
|
|
||||||
data.append(
|
|
||||||
{
|
|
||||||
"name": _("SAML Provider from Metadata"),
|
|
||||||
"description": _("Create a SAML Provider by importing its Metadata."),
|
|
||||||
"component": "ak-provider-saml-import-form",
|
|
||||||
"model_name": "",
|
|
||||||
}
|
|
||||||
)
|
|
||||||
return Response(TypeCreateSerializer(data, many=True).data)
|
|
||||||
|
@ -11,14 +11,14 @@ from rest_framework.filters import OrderingFilter, SearchFilter
|
|||||||
from rest_framework.parsers import MultiPartParser
|
from rest_framework.parsers import MultiPartParser
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.serializers import ModelSerializer
|
|
||||||
from rest_framework.viewsets import GenericViewSet
|
from rest_framework.viewsets import GenericViewSet
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik.api.authorization import OwnerFilter, OwnerSuperuserPermissions
|
from authentik.api.authorization import OwnerFilter, OwnerSuperuserPermissions
|
||||||
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT
|
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT
|
||||||
|
from authentik.core.api.object_types import TypesMixin
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.utils import MetaNameSerializer, TypeCreateSerializer
|
from authentik.core.api.utils import MetaNameSerializer, ModelSerializer
|
||||||
from authentik.core.models import Source, UserSourceConnection
|
from authentik.core.models import Source, UserSourceConnection
|
||||||
from authentik.core.types import UserSettingSerializer
|
from authentik.core.types import UserSettingSerializer
|
||||||
from authentik.lib.utils.file import (
|
from authentik.lib.utils.file import (
|
||||||
@ -27,7 +27,6 @@ from authentik.lib.utils.file import (
|
|||||||
set_file,
|
set_file,
|
||||||
set_file_url,
|
set_file_url,
|
||||||
)
|
)
|
||||||
from authentik.lib.utils.reflection import all_subclasses
|
|
||||||
from authentik.policies.engine import PolicyEngine
|
from authentik.policies.engine import PolicyEngine
|
||||||
from authentik.rbac.decorators import permission_required
|
from authentik.rbac.decorators import permission_required
|
||||||
|
|
||||||
@ -74,6 +73,7 @@ class SourceSerializer(ModelSerializer, MetaNameSerializer):
|
|||||||
|
|
||||||
|
|
||||||
class SourceViewSet(
|
class SourceViewSet(
|
||||||
|
TypesMixin,
|
||||||
mixins.RetrieveModelMixin,
|
mixins.RetrieveModelMixin,
|
||||||
mixins.DestroyModelMixin,
|
mixins.DestroyModelMixin,
|
||||||
UsedByMixin,
|
UsedByMixin,
|
||||||
@ -132,30 +132,6 @@ class SourceViewSet(
|
|||||||
source: Source = self.get_object()
|
source: Source = self.get_object()
|
||||||
return set_file_url(request, source, "icon")
|
return set_file_url(request, source, "icon")
|
||||||
|
|
||||||
@extend_schema(responses={200: TypeCreateSerializer(many=True)})
|
|
||||||
@action(detail=False, pagination_class=None, filter_backends=[])
|
|
||||||
def types(self, request: Request) -> Response:
|
|
||||||
"""Get all creatable source types"""
|
|
||||||
data = []
|
|
||||||
for subclass in all_subclasses(self.queryset.model):
|
|
||||||
subclass: Source
|
|
||||||
component = ""
|
|
||||||
if len(subclass.__subclasses__()) > 0:
|
|
||||||
continue
|
|
||||||
if subclass._meta.abstract:
|
|
||||||
component = subclass.__bases__[0]().component
|
|
||||||
else:
|
|
||||||
component = subclass().component
|
|
||||||
data.append(
|
|
||||||
{
|
|
||||||
"name": subclass._meta.verbose_name,
|
|
||||||
"description": subclass.__doc__,
|
|
||||||
"component": component,
|
|
||||||
"model_name": subclass._meta.model_name,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
return Response(TypeCreateSerializer(data, many=True).data)
|
|
||||||
|
|
||||||
@extend_schema(responses={200: UserSettingSerializer(many=True)})
|
@extend_schema(responses={200: UserSettingSerializer(many=True)})
|
||||||
@action(detail=False, pagination_class=None, filter_backends=[])
|
@action(detail=False, pagination_class=None, filter_backends=[])
|
||||||
def user_settings(self, request: Request) -> Response:
|
def user_settings(self, request: Request) -> Response:
|
||||||
|
@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
from django.utils.timezone import now
|
||||||
from django_filters.rest_framework import DjangoFilterBackend
|
from django_filters.rest_framework import DjangoFilterBackend
|
||||||
from drf_spectacular.utils import OpenApiResponse, extend_schema, inline_serializer
|
from drf_spectacular.utils import OpenApiResponse, extend_schema, inline_serializer
|
||||||
from guardian.shortcuts import assign_perm, get_anonymous_user
|
from guardian.shortcuts import assign_perm, get_anonymous_user
|
||||||
@ -11,7 +12,6 @@ from rest_framework.fields import CharField
|
|||||||
from rest_framework.filters import OrderingFilter, SearchFilter
|
from rest_framework.filters import OrderingFilter, SearchFilter
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.serializers import ModelSerializer
|
|
||||||
from rest_framework.viewsets import ModelViewSet
|
from rest_framework.viewsets import ModelViewSet
|
||||||
|
|
||||||
from authentik.api.authorization import OwnerSuperuserPermissions
|
from authentik.api.authorization import OwnerSuperuserPermissions
|
||||||
@ -19,10 +19,18 @@ from authentik.blueprints.api import ManagedSerializer
|
|||||||
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT
|
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.users import UserSerializer
|
from authentik.core.api.users import UserSerializer
|
||||||
from authentik.core.api.utils import PassiveSerializer
|
from authentik.core.api.utils import ModelSerializer, PassiveSerializer
|
||||||
from authentik.core.models import USER_ATTRIBUTE_TOKEN_EXPIRING, Token, TokenIntents
|
from authentik.core.models import (
|
||||||
|
USER_ATTRIBUTE_TOKEN_EXPIRING,
|
||||||
|
USER_ATTRIBUTE_TOKEN_MAXIMUM_LIFETIME,
|
||||||
|
Token,
|
||||||
|
TokenIntents,
|
||||||
|
User,
|
||||||
|
default_token_duration,
|
||||||
|
)
|
||||||
from authentik.events.models import Event, EventAction
|
from authentik.events.models import Event, EventAction
|
||||||
from authentik.events.utils import model_to_dict
|
from authentik.events.utils import model_to_dict
|
||||||
|
from authentik.lib.utils.time import timedelta_from_string
|
||||||
from authentik.rbac.decorators import permission_required
|
from authentik.rbac.decorators import permission_required
|
||||||
|
|
||||||
|
|
||||||
@ -36,6 +44,13 @@ class TokenSerializer(ManagedSerializer, ModelSerializer):
|
|||||||
if SERIALIZER_CONTEXT_BLUEPRINT in self.context:
|
if SERIALIZER_CONTEXT_BLUEPRINT in self.context:
|
||||||
self.fields["key"] = CharField(required=False)
|
self.fields["key"] = CharField(required=False)
|
||||||
|
|
||||||
|
def validate_user(self, user: User):
|
||||||
|
"""Ensure user of token cannot be changed"""
|
||||||
|
if self.instance and self.instance.user_id:
|
||||||
|
if user.pk != self.instance.user_id:
|
||||||
|
raise ValidationError("User cannot be changed")
|
||||||
|
return user
|
||||||
|
|
||||||
def validate(self, attrs: dict[Any, str]) -> dict[Any, str]:
|
def validate(self, attrs: dict[Any, str]) -> dict[Any, str]:
|
||||||
"""Ensure only API or App password tokens are created."""
|
"""Ensure only API or App password tokens are created."""
|
||||||
request: Request = self.context.get("request")
|
request: Request = self.context.get("request")
|
||||||
@ -49,6 +64,32 @@ class TokenSerializer(ManagedSerializer, ModelSerializer):
|
|||||||
attrs.setdefault("intent", TokenIntents.INTENT_API)
|
attrs.setdefault("intent", TokenIntents.INTENT_API)
|
||||||
if attrs.get("intent") not in [TokenIntents.INTENT_API, TokenIntents.INTENT_APP_PASSWORD]:
|
if attrs.get("intent") not in [TokenIntents.INTENT_API, TokenIntents.INTENT_APP_PASSWORD]:
|
||||||
raise ValidationError({"intent": f"Invalid intent {attrs.get('intent')}"})
|
raise ValidationError({"intent": f"Invalid intent {attrs.get('intent')}"})
|
||||||
|
|
||||||
|
if attrs.get("intent") == TokenIntents.INTENT_APP_PASSWORD:
|
||||||
|
# user IS in attrs
|
||||||
|
user: User = attrs.get("user")
|
||||||
|
max_token_lifetime = user.group_attributes(request).get(
|
||||||
|
USER_ATTRIBUTE_TOKEN_MAXIMUM_LIFETIME,
|
||||||
|
)
|
||||||
|
max_token_lifetime_dt = default_token_duration()
|
||||||
|
if max_token_lifetime is not None:
|
||||||
|
try:
|
||||||
|
max_token_lifetime_dt = now() + timedelta_from_string(max_token_lifetime)
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if "expires" in attrs and attrs.get("expires") > max_token_lifetime_dt:
|
||||||
|
raise ValidationError(
|
||||||
|
{
|
||||||
|
"expires": (
|
||||||
|
f"Token expires exceeds maximum lifetime ({max_token_lifetime_dt} UTC)."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
elif attrs.get("intent") == TokenIntents.INTENT_API:
|
||||||
|
# For API tokens, expires cannot be overridden
|
||||||
|
attrs["expires"] = default_token_duration()
|
||||||
|
|
||||||
return attrs
|
return attrs
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
|
@ -39,12 +39,12 @@ def get_delete_action(manager: Manager) -> str:
|
|||||||
"""Get the delete action from the Foreign key, falls back to cascade"""
|
"""Get the delete action from the Foreign key, falls back to cascade"""
|
||||||
if hasattr(manager, "field"):
|
if hasattr(manager, "field"):
|
||||||
if manager.field.remote_field.on_delete.__name__ == SET_NULL.__name__:
|
if manager.field.remote_field.on_delete.__name__ == SET_NULL.__name__:
|
||||||
return DeleteAction.SET_NULL.name
|
return DeleteAction.SET_NULL.value
|
||||||
if manager.field.remote_field.on_delete.__name__ == SET_DEFAULT.__name__:
|
if manager.field.remote_field.on_delete.__name__ == SET_DEFAULT.__name__:
|
||||||
return DeleteAction.SET_DEFAULT.name
|
return DeleteAction.SET_DEFAULT.value
|
||||||
if hasattr(manager, "source_field"):
|
if hasattr(manager, "source_field"):
|
||||||
return DeleteAction.CASCADE_MANY.name
|
return DeleteAction.CASCADE_MANY.value
|
||||||
return DeleteAction.CASCADE.name
|
return DeleteAction.CASCADE.value
|
||||||
|
|
||||||
|
|
||||||
class UsedByMixin:
|
class UsedByMixin:
|
||||||
|
@ -40,7 +40,6 @@ from rest_framework.serializers import (
|
|||||||
BooleanField,
|
BooleanField,
|
||||||
DateTimeField,
|
DateTimeField,
|
||||||
ListSerializer,
|
ListSerializer,
|
||||||
ModelSerializer,
|
|
||||||
PrimaryKeyRelatedField,
|
PrimaryKeyRelatedField,
|
||||||
ValidationError,
|
ValidationError,
|
||||||
)
|
)
|
||||||
@ -52,7 +51,12 @@ from authentik.admin.api.metrics import CoordinateSerializer
|
|||||||
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT
|
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT
|
||||||
from authentik.brands.models import Brand
|
from authentik.brands.models import Brand
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.utils import JSONDictField, LinkSerializer, PassiveSerializer
|
from authentik.core.api.utils import (
|
||||||
|
JSONDictField,
|
||||||
|
LinkSerializer,
|
||||||
|
ModelSerializer,
|
||||||
|
PassiveSerializer,
|
||||||
|
)
|
||||||
from authentik.core.middleware import (
|
from authentik.core.middleware import (
|
||||||
SESSION_KEY_IMPERSONATE_ORIGINAL_USER,
|
SESSION_KEY_IMPERSONATE_ORIGINAL_USER,
|
||||||
SESSION_KEY_IMPERSONATE_USER,
|
SESSION_KEY_IMPERSONATE_USER,
|
||||||
@ -85,7 +89,7 @@ class UserGroupSerializer(ModelSerializer):
|
|||||||
"""Simplified Group Serializer for user's groups"""
|
"""Simplified Group Serializer for user's groups"""
|
||||||
|
|
||||||
attributes = JSONDictField(required=False)
|
attributes = JSONDictField(required=False)
|
||||||
parent_name = CharField(source="parent.name", read_only=True)
|
parent_name = CharField(source="parent.name", read_only=True, allow_null=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = Group
|
model = Group
|
||||||
@ -113,13 +117,26 @@ class UserSerializer(ModelSerializer):
|
|||||||
queryset=Group.objects.all().order_by("name"),
|
queryset=Group.objects.all().order_by("name"),
|
||||||
default=list,
|
default=list,
|
||||||
)
|
)
|
||||||
groups_obj = ListSerializer(child=UserGroupSerializer(), read_only=True, source="ak_groups")
|
groups_obj = SerializerMethodField(allow_null=True)
|
||||||
uid = CharField(read_only=True)
|
uid = CharField(read_only=True)
|
||||||
username = CharField(
|
username = CharField(
|
||||||
max_length=150,
|
max_length=150,
|
||||||
validators=[UniqueValidator(queryset=User.objects.all().order_by("username"))],
|
validators=[UniqueValidator(queryset=User.objects.all().order_by("username"))],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def _should_include_groups(self) -> bool:
|
||||||
|
request: Request = self.context.get("request", None)
|
||||||
|
if not request:
|
||||||
|
return True
|
||||||
|
return str(request.query_params.get("include_groups", "true")).lower() == "true"
|
||||||
|
|
||||||
|
@extend_schema_field(UserGroupSerializer(many=True))
|
||||||
|
def get_groups_obj(self, instance: User) -> list[UserGroupSerializer] | None:
|
||||||
|
if not self._should_include_groups:
|
||||||
|
return None
|
||||||
|
return UserGroupSerializer(instance.ak_groups, many=True).data
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
super().__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
if SERIALIZER_CONTEXT_BLUEPRINT in self.context:
|
if SERIALIZER_CONTEXT_BLUEPRINT in self.context:
|
||||||
@ -394,8 +411,19 @@ class UserViewSet(UsedByMixin, ModelViewSet):
|
|||||||
search_fields = ["username", "name", "is_active", "email", "uuid"]
|
search_fields = ["username", "name", "is_active", "email", "uuid"]
|
||||||
filterset_class = UsersFilter
|
filterset_class = UsersFilter
|
||||||
|
|
||||||
def get_queryset(self): # pragma: no cover
|
def get_queryset(self):
|
||||||
return User.objects.all().exclude_anonymous().prefetch_related("ak_groups")
|
base_qs = User.objects.all().exclude_anonymous()
|
||||||
|
if self.serializer_class(context={"request": self.request})._should_include_groups:
|
||||||
|
base_qs = base_qs.prefetch_related("ak_groups")
|
||||||
|
return base_qs
|
||||||
|
|
||||||
|
@extend_schema(
|
||||||
|
parameters=[
|
||||||
|
OpenApiParameter("include_groups", bool, default=True),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
def list(self, request, *args, **kwargs):
|
||||||
|
return super().list(request, *args, **kwargs)
|
||||||
|
|
||||||
def _create_recovery_link(self) -> tuple[str, Token]:
|
def _create_recovery_link(self) -> tuple[str, Token]:
|
||||||
"""Create a recovery link (when the current brand has a recovery flow set),
|
"""Create a recovery link (when the current brand has a recovery flow set),
|
||||||
@ -605,7 +633,7 @@ class UserViewSet(UsedByMixin, ModelViewSet):
|
|||||||
email_stage: EmailStage = stages.first()
|
email_stage: EmailStage = stages.first()
|
||||||
message = TemplateEmailMessage(
|
message = TemplateEmailMessage(
|
||||||
subject=_(email_stage.subject),
|
subject=_(email_stage.subject),
|
||||||
to=[for_user.email],
|
to=[(for_user.name, for_user.email)],
|
||||||
template_name=email_stage.template,
|
template_name=email_stage.template,
|
||||||
language=for_user.locale(request),
|
language=for_user.locale(request),
|
||||||
template_context={
|
template_context={
|
||||||
|
@ -6,8 +6,19 @@ from django.db.models import Model
|
|||||||
from drf_spectacular.extensions import OpenApiSerializerFieldExtension
|
from drf_spectacular.extensions import OpenApiSerializerFieldExtension
|
||||||
from drf_spectacular.plumbing import build_basic_type
|
from drf_spectacular.plumbing import build_basic_type
|
||||||
from drf_spectacular.types import OpenApiTypes
|
from drf_spectacular.types import OpenApiTypes
|
||||||
from rest_framework.fields import BooleanField, CharField, IntegerField, JSONField
|
from rest_framework.fields import (
|
||||||
from rest_framework.serializers import Serializer, SerializerMethodField, ValidationError
|
CharField,
|
||||||
|
IntegerField,
|
||||||
|
JSONField,
|
||||||
|
SerializerMethodField,
|
||||||
|
)
|
||||||
|
from rest_framework.serializers import ModelSerializer as BaseModelSerializer
|
||||||
|
from rest_framework.serializers import (
|
||||||
|
Serializer,
|
||||||
|
ValidationError,
|
||||||
|
model_meta,
|
||||||
|
raise_errors_on_nested_writes,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def is_dict(value: Any):
|
def is_dict(value: Any):
|
||||||
@ -17,6 +28,39 @@ def is_dict(value: Any):
|
|||||||
raise ValidationError("Value must be a dictionary, and not have any duplicate keys.")
|
raise ValidationError("Value must be a dictionary, and not have any duplicate keys.")
|
||||||
|
|
||||||
|
|
||||||
|
class ModelSerializer(BaseModelSerializer):
|
||||||
|
|
||||||
|
def update(self, instance: Model, validated_data):
|
||||||
|
raise_errors_on_nested_writes("update", self, validated_data)
|
||||||
|
info = model_meta.get_field_info(instance)
|
||||||
|
|
||||||
|
# Simply set each attribute on the instance, and then save it.
|
||||||
|
# Note that unlike `.create()` we don't need to treat many-to-many
|
||||||
|
# relationships as being a special case. During updates we already
|
||||||
|
# have an instance pk for the relationships to be associated with.
|
||||||
|
m2m_fields = []
|
||||||
|
for attr, value in validated_data.items():
|
||||||
|
if attr in info.relations and info.relations[attr].to_many:
|
||||||
|
m2m_fields.append((attr, value))
|
||||||
|
else:
|
||||||
|
setattr(instance, attr, value)
|
||||||
|
|
||||||
|
instance.save()
|
||||||
|
|
||||||
|
# Note that many-to-many fields are set after updating instance.
|
||||||
|
# Setting m2m fields triggers signals which could potentially change
|
||||||
|
# updated instance and we do not want it to collide with .update()
|
||||||
|
for attr, value in m2m_fields:
|
||||||
|
field = getattr(instance, attr)
|
||||||
|
# We can't check for inheritance here as m2m managers are generated dynamically
|
||||||
|
if field.__class__.__name__ == "RelatedManager":
|
||||||
|
field.set(value, bulk=False)
|
||||||
|
else:
|
||||||
|
field.set(value)
|
||||||
|
|
||||||
|
return instance
|
||||||
|
|
||||||
|
|
||||||
class JSONDictField(JSONField):
|
class JSONDictField(JSONField):
|
||||||
"""JSON Field which only allows dictionaries"""
|
"""JSON Field which only allows dictionaries"""
|
||||||
|
|
||||||
@ -68,16 +112,6 @@ class MetaNameSerializer(PassiveSerializer):
|
|||||||
return f"{obj._meta.app_label}.{obj._meta.model_name}"
|
return f"{obj._meta.app_label}.{obj._meta.model_name}"
|
||||||
|
|
||||||
|
|
||||||
class TypeCreateSerializer(PassiveSerializer):
|
|
||||||
"""Types of an object that can be created"""
|
|
||||||
|
|
||||||
name = CharField(required=True)
|
|
||||||
description = CharField(required=True)
|
|
||||||
component = CharField(required=True)
|
|
||||||
model_name = CharField(required=True)
|
|
||||||
requires_enterprise = BooleanField(default=False)
|
|
||||||
|
|
||||||
|
|
||||||
class CacheSerializer(PassiveSerializer):
|
class CacheSerializer(PassiveSerializer):
|
||||||
"""Generic cache stats for an object"""
|
"""Generic cache stats for an object"""
|
||||||
|
|
||||||
|
@ -31,8 +31,9 @@ class InbuiltBackend(ModelBackend):
|
|||||||
# Since we can't directly pass other variables to signals, and we want to log the method
|
# Since we can't directly pass other variables to signals, and we want to log the method
|
||||||
# and the token used, we assume we're running in a flow and set a variable in the context
|
# and the token used, we assume we're running in a flow and set a variable in the context
|
||||||
flow_plan: FlowPlan = request.session.get(SESSION_KEY_PLAN, FlowPlan(""))
|
flow_plan: FlowPlan = request.session.get(SESSION_KEY_PLAN, FlowPlan(""))
|
||||||
flow_plan.context[PLAN_CONTEXT_METHOD] = method
|
flow_plan.context.setdefault(PLAN_CONTEXT_METHOD, method)
|
||||||
flow_plan.context[PLAN_CONTEXT_METHOD_ARGS] = cleanse_dict(sanitize_dict(kwargs))
|
flow_plan.context.setdefault(PLAN_CONTEXT_METHOD_ARGS, {})
|
||||||
|
flow_plan.context[PLAN_CONTEXT_METHOD_ARGS].update(cleanse_dict(sanitize_dict(kwargs)))
|
||||||
request.session[SESSION_KEY_PLAN] = flow_plan
|
request.session[SESSION_KEY_PLAN] = flow_plan
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,7 +0,0 @@
|
|||||||
"""authentik core exceptions"""
|
|
||||||
|
|
||||||
from authentik.lib.sentry import SentryIgnoredException
|
|
||||||
|
|
||||||
|
|
||||||
class PropertyMappingExpressionException(SentryIgnoredException):
|
|
||||||
"""Error when a PropertyMapping Exception expression could not be parsed or evaluated."""
|
|
@ -1,11 +1,13 @@
|
|||||||
"""Property Mapping Evaluator"""
|
"""Property Mapping Evaluator"""
|
||||||
|
|
||||||
|
from types import CodeType
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from django.db.models import Model
|
from django.db.models import Model
|
||||||
from django.http import HttpRequest
|
from django.http import HttpRequest
|
||||||
from prometheus_client import Histogram
|
from prometheus_client import Histogram
|
||||||
|
|
||||||
|
from authentik.core.expression.exceptions import SkipObjectException
|
||||||
from authentik.core.models import User
|
from authentik.core.models import User
|
||||||
from authentik.events.models import Event, EventAction
|
from authentik.events.models import Event, EventAction
|
||||||
from authentik.lib.expression.evaluator import BaseEvaluator
|
from authentik.lib.expression.evaluator import BaseEvaluator
|
||||||
@ -23,6 +25,8 @@ class PropertyMappingEvaluator(BaseEvaluator):
|
|||||||
"""Custom Evaluator that adds some different context variables."""
|
"""Custom Evaluator that adds some different context variables."""
|
||||||
|
|
||||||
dry_run: bool
|
dry_run: bool
|
||||||
|
model: Model
|
||||||
|
_compiled: CodeType | None = None
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
@ -32,22 +36,32 @@ class PropertyMappingEvaluator(BaseEvaluator):
|
|||||||
dry_run: bool | None = False,
|
dry_run: bool | None = False,
|
||||||
**kwargs,
|
**kwargs,
|
||||||
):
|
):
|
||||||
|
self.model = model
|
||||||
if hasattr(model, "name"):
|
if hasattr(model, "name"):
|
||||||
_filename = model.name
|
_filename = model.name
|
||||||
else:
|
else:
|
||||||
_filename = str(model)
|
_filename = str(model)
|
||||||
super().__init__(filename=_filename)
|
super().__init__(filename=_filename)
|
||||||
|
self.dry_run = dry_run
|
||||||
|
self.set_context(user, request, **kwargs)
|
||||||
|
|
||||||
|
def set_context(
|
||||||
|
self,
|
||||||
|
user: User | None = None,
|
||||||
|
request: HttpRequest | None = None,
|
||||||
|
**kwargs,
|
||||||
|
):
|
||||||
req = PolicyRequest(user=User())
|
req = PolicyRequest(user=User())
|
||||||
req.obj = model
|
req.obj = self.model
|
||||||
if user:
|
if user:
|
||||||
req.user = user
|
req.user = user
|
||||||
self._context["user"] = user
|
self._context["user"] = user
|
||||||
if request:
|
if request:
|
||||||
req.http_request = request
|
req.http_request = request
|
||||||
self._context["request"] = req
|
|
||||||
req.context.update(**kwargs)
|
req.context.update(**kwargs)
|
||||||
|
self._context["request"] = req
|
||||||
self._context.update(**kwargs)
|
self._context.update(**kwargs)
|
||||||
self.dry_run = dry_run
|
self._globals["SkipObject"] = SkipObjectException
|
||||||
|
|
||||||
def handle_error(self, exc: Exception, expression_source: str):
|
def handle_error(self, exc: Exception, expression_source: str):
|
||||||
"""Exception Handler"""
|
"""Exception Handler"""
|
||||||
@ -62,10 +76,19 @@ class PropertyMappingEvaluator(BaseEvaluator):
|
|||||||
)
|
)
|
||||||
if "request" in self._context:
|
if "request" in self._context:
|
||||||
req: PolicyRequest = self._context["request"]
|
req: PolicyRequest = self._context["request"]
|
||||||
event.from_http(req.http_request, req.user)
|
if req.http_request:
|
||||||
return
|
event.from_http(req.http_request, req.user)
|
||||||
|
return
|
||||||
|
elif req.user:
|
||||||
|
event.set_user(req.user)
|
||||||
event.save()
|
event.save()
|
||||||
|
|
||||||
def evaluate(self, *args, **kwargs) -> Any:
|
def evaluate(self, *args, **kwargs) -> Any:
|
||||||
with PROPERTY_MAPPING_TIME.labels(mapping_name=self._filename).time():
|
with PROPERTY_MAPPING_TIME.labels(mapping_name=self._filename).time():
|
||||||
return super().evaluate(*args, **kwargs)
|
return super().evaluate(*args, **kwargs)
|
||||||
|
|
||||||
|
def compile(self, expression: str | None = None) -> Any:
|
||||||
|
if not self._compiled:
|
||||||
|
compiled = super().compile(expression or self.model.expression)
|
||||||
|
self._compiled = compiled
|
||||||
|
return self._compiled
|
||||||
|
19
authentik/core/expression/exceptions.py
Normal file
19
authentik/core/expression/exceptions.py
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
"""authentik core exceptions"""
|
||||||
|
|
||||||
|
from authentik.lib.expression.exceptions import ControlFlowException
|
||||||
|
from authentik.lib.sentry import SentryIgnoredException
|
||||||
|
|
||||||
|
|
||||||
|
class PropertyMappingExpressionException(SentryIgnoredException):
|
||||||
|
"""Error when a PropertyMapping Exception expression could not be parsed or evaluated."""
|
||||||
|
|
||||||
|
def __init__(self, exc: Exception, mapping) -> None:
|
||||||
|
super().__init__()
|
||||||
|
self.exc = exc
|
||||||
|
self.mapping = mapping
|
||||||
|
|
||||||
|
|
||||||
|
class SkipObjectException(ControlFlowException):
|
||||||
|
"""Exception which can be raised in a property mapping to skip syncing an object.
|
||||||
|
Only applies to Property mappings which sync objects, and not on mappings which transitively
|
||||||
|
apply to a single user"""
|
@ -1,10 +1,34 @@
|
|||||||
"""custom runserver command"""
|
"""custom runserver command"""
|
||||||
|
|
||||||
|
from typing import TextIO
|
||||||
|
|
||||||
from daphne.management.commands.runserver import Command as RunServer
|
from daphne.management.commands.runserver import Command as RunServer
|
||||||
|
from daphne.server import Server
|
||||||
|
|
||||||
|
from authentik.root.signals import post_startup, pre_startup, startup
|
||||||
|
|
||||||
|
|
||||||
|
class SignalServer(Server):
|
||||||
|
"""Server which signals back to authentik when it finished starting up"""
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
|
||||||
|
def ready_callable():
|
||||||
|
pre_startup.send(sender=self)
|
||||||
|
startup.send(sender=self)
|
||||||
|
post_startup.send(sender=self)
|
||||||
|
|
||||||
|
self.ready_callable = ready_callable
|
||||||
|
|
||||||
|
|
||||||
class Command(RunServer):
|
class Command(RunServer):
|
||||||
"""custom runserver command, which doesn't show the misleading django startup message"""
|
"""custom runserver command, which doesn't show the misleading django startup message"""
|
||||||
|
|
||||||
def on_bind(self, server_port):
|
server_cls = SignalServer
|
||||||
pass
|
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
# Redirect standard stdout banner from Daphne into the void
|
||||||
|
# as there are a couple more steps that happen before startup is fully done
|
||||||
|
self.stdout = TextIO()
|
||||||
|
@ -5,6 +5,7 @@ from django.db import migrations, models
|
|||||||
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
|
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
|
||||||
|
|
||||||
import authentik.core.models
|
import authentik.core.models
|
||||||
|
from authentik.lib.generators import generate_id
|
||||||
|
|
||||||
|
|
||||||
def set_default_token_key(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
|
def set_default_token_key(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
|
||||||
@ -16,6 +17,10 @@ def set_default_token_key(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
|
|||||||
token.save()
|
token.save()
|
||||||
|
|
||||||
|
|
||||||
|
def default_token_key():
|
||||||
|
return generate_id(60)
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
class Migration(migrations.Migration):
|
||||||
replaces = [
|
replaces = [
|
||||||
("authentik_core", "0012_auto_20201003_1737"),
|
("authentik_core", "0012_auto_20201003_1737"),
|
||||||
@ -62,7 +67,7 @@ class Migration(migrations.Migration):
|
|||||||
migrations.AddField(
|
migrations.AddField(
|
||||||
model_name="token",
|
model_name="token",
|
||||||
name="key",
|
name="key",
|
||||||
field=models.TextField(default=authentik.core.models.default_token_key),
|
field=models.TextField(default=default_token_key),
|
||||||
),
|
),
|
||||||
migrations.AlterUniqueTogether(
|
migrations.AlterUniqueTogether(
|
||||||
name="token",
|
name="token",
|
||||||
|
@ -7,11 +7,13 @@ from django.db.backends.base.schema import BaseDatabaseSchemaEditor
|
|||||||
|
|
||||||
|
|
||||||
def backport_is_backchannel(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
|
def backport_is_backchannel(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
|
||||||
from authentik.core.models import BackchannelProvider
|
db_alias = schema_editor.connection.alias
|
||||||
|
from authentik.providers.ldap.models import LDAPProvider
|
||||||
|
from authentik.providers.scim.models import SCIMProvider
|
||||||
|
|
||||||
for model in BackchannelProvider.__subclasses__():
|
for model in [LDAPProvider, SCIMProvider]:
|
||||||
try:
|
try:
|
||||||
for obj in model.objects.only("is_backchannel"):
|
for obj in model.objects.using(db_alias).only("is_backchannel"):
|
||||||
obj.is_backchannel = True
|
obj.is_backchannel = True
|
||||||
obj.save()
|
obj.save()
|
||||||
except (DatabaseError, InternalError, ProgrammingError):
|
except (DatabaseError, InternalError, ProgrammingError):
|
||||||
|
@ -0,0 +1,31 @@
|
|||||||
|
# Generated by Django 5.0.2 on 2024-02-29 10:15
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
import authentik.core.models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
("authentik_core", "0033_alter_user_options"),
|
||||||
|
("authentik_tenants", "0002_tenant_default_token_duration_and_more"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name="authenticatedsession",
|
||||||
|
name="expires",
|
||||||
|
field=models.DateTimeField(default=None, null=True),
|
||||||
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name="token",
|
||||||
|
name="expires",
|
||||||
|
field=models.DateTimeField(default=None, null=True),
|
||||||
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name="token",
|
||||||
|
name="key",
|
||||||
|
field=models.TextField(default=authentik.core.models.default_token_key),
|
||||||
|
),
|
||||||
|
]
|
@ -0,0 +1,52 @@
|
|||||||
|
# Generated by Django 5.0.4 on 2024-04-15 11:28
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
("auth", "0012_alter_user_first_name_max_length"),
|
||||||
|
("authentik_core", "0034_alter_authenticatedsession_expires_and_more"),
|
||||||
|
("authentik_rbac", "0003_alter_systempermission_options"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AlterModelOptions(
|
||||||
|
name="group",
|
||||||
|
options={
|
||||||
|
"permissions": [
|
||||||
|
("add_user_to_group", "Add user to group"),
|
||||||
|
("remove_user_from_group", "Remove user from group"),
|
||||||
|
],
|
||||||
|
"verbose_name": "Group",
|
||||||
|
"verbose_name_plural": "Groups",
|
||||||
|
},
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="group",
|
||||||
|
index=models.Index(fields=["name"], name="authentik_c_name_9ba8e4_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="user",
|
||||||
|
index=models.Index(fields=["last_login"], name="authentik_c_last_lo_f0179a_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="user",
|
||||||
|
index=models.Index(
|
||||||
|
fields=["password_change_date"], name="authentik_c_passwor_eec915_idx"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="user",
|
||||||
|
index=models.Index(fields=["uuid"], name="authentik_c_uuid_3dae2f_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="user",
|
||||||
|
index=models.Index(fields=["path"], name="authentik_c_path_b1f502_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="user",
|
||||||
|
index=models.Index(fields=["type"], name="authentik_c_type_ecf60d_idx"),
|
||||||
|
),
|
||||||
|
]
|
@ -1,6 +1,6 @@
|
|||||||
"""authentik core models"""
|
"""authentik core models"""
|
||||||
|
|
||||||
from datetime import timedelta
|
from datetime import datetime
|
||||||
from hashlib import sha256
|
from hashlib import sha256
|
||||||
from typing import Any, Optional, Self
|
from typing import Any, Optional, Self
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
@ -15,6 +15,7 @@ from django.http import HttpRequest
|
|||||||
from django.utils.functional import SimpleLazyObject, cached_property
|
from django.utils.functional import SimpleLazyObject, cached_property
|
||||||
from django.utils.timezone import now
|
from django.utils.timezone import now
|
||||||
from django.utils.translation import gettext_lazy as _
|
from django.utils.translation import gettext_lazy as _
|
||||||
|
from django_cte import CTEQuerySet, With
|
||||||
from guardian.conf import settings
|
from guardian.conf import settings
|
||||||
from guardian.mixins import GuardianUserMixin
|
from guardian.mixins import GuardianUserMixin
|
||||||
from model_utils.managers import InheritanceManager
|
from model_utils.managers import InheritanceManager
|
||||||
@ -22,18 +23,20 @@ from rest_framework.serializers import Serializer
|
|||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik.blueprints.models import ManagedModel
|
from authentik.blueprints.models import ManagedModel
|
||||||
from authentik.core.exceptions import PropertyMappingExpressionException
|
from authentik.core.expression.exceptions import PropertyMappingExpressionException
|
||||||
from authentik.core.types import UILoginButton, UserSettingSerializer
|
from authentik.core.types import UILoginButton, UserSettingSerializer
|
||||||
from authentik.lib.avatars import get_avatar
|
from authentik.lib.avatars import get_avatar
|
||||||
from authentik.lib.config import CONFIG
|
from authentik.lib.expression.exceptions import ControlFlowException
|
||||||
from authentik.lib.generators import generate_id
|
from authentik.lib.generators import generate_id
|
||||||
from authentik.lib.models import (
|
from authentik.lib.models import (
|
||||||
CreatedUpdatedModel,
|
CreatedUpdatedModel,
|
||||||
DomainlessFormattedURLValidator,
|
DomainlessFormattedURLValidator,
|
||||||
SerializerModel,
|
SerializerModel,
|
||||||
)
|
)
|
||||||
|
from authentik.lib.utils.time import timedelta_from_string
|
||||||
from authentik.policies.models import PolicyBindingModel
|
from authentik.policies.models import PolicyBindingModel
|
||||||
from authentik.root.install_id import get_install_id
|
from authentik.tenants.models import DEFAULT_TOKEN_DURATION, DEFAULT_TOKEN_LENGTH
|
||||||
|
from authentik.tenants.utils import get_current_tenant, get_unique_identifier
|
||||||
|
|
||||||
LOGGER = get_logger()
|
LOGGER = get_logger()
|
||||||
USER_ATTRIBUTE_DEBUG = "goauthentik.io/user/debug"
|
USER_ATTRIBUTE_DEBUG = "goauthentik.io/user/debug"
|
||||||
@ -42,33 +45,44 @@ USER_ATTRIBUTE_EXPIRES = "goauthentik.io/user/expires"
|
|||||||
USER_ATTRIBUTE_DELETE_ON_LOGOUT = "goauthentik.io/user/delete-on-logout"
|
USER_ATTRIBUTE_DELETE_ON_LOGOUT = "goauthentik.io/user/delete-on-logout"
|
||||||
USER_ATTRIBUTE_SOURCES = "goauthentik.io/user/sources"
|
USER_ATTRIBUTE_SOURCES = "goauthentik.io/user/sources"
|
||||||
USER_ATTRIBUTE_TOKEN_EXPIRING = "goauthentik.io/user/token-expires" # nosec
|
USER_ATTRIBUTE_TOKEN_EXPIRING = "goauthentik.io/user/token-expires" # nosec
|
||||||
|
USER_ATTRIBUTE_TOKEN_MAXIMUM_LIFETIME = "goauthentik.io/user/token-maximum-lifetime" # nosec
|
||||||
USER_ATTRIBUTE_CHANGE_USERNAME = "goauthentik.io/user/can-change-username"
|
USER_ATTRIBUTE_CHANGE_USERNAME = "goauthentik.io/user/can-change-username"
|
||||||
USER_ATTRIBUTE_CHANGE_NAME = "goauthentik.io/user/can-change-name"
|
USER_ATTRIBUTE_CHANGE_NAME = "goauthentik.io/user/can-change-name"
|
||||||
USER_ATTRIBUTE_CHANGE_EMAIL = "goauthentik.io/user/can-change-email"
|
USER_ATTRIBUTE_CHANGE_EMAIL = "goauthentik.io/user/can-change-email"
|
||||||
USER_PATH_SYSTEM_PREFIX = "goauthentik.io"
|
USER_PATH_SYSTEM_PREFIX = "goauthentik.io"
|
||||||
USER_PATH_SERVICE_ACCOUNT = USER_PATH_SYSTEM_PREFIX + "/service-accounts"
|
USER_PATH_SERVICE_ACCOUNT = USER_PATH_SYSTEM_PREFIX + "/service-accounts"
|
||||||
|
|
||||||
|
|
||||||
options.DEFAULT_NAMES = options.DEFAULT_NAMES + (
|
options.DEFAULT_NAMES = options.DEFAULT_NAMES + (
|
||||||
# used_by API that allows models to specify if they shadow an object
|
# used_by API that allows models to specify if they shadow an object
|
||||||
# for example the proxy provider which is built on top of an oauth provider
|
# for example the proxy provider which is built on top of an oauth provider
|
||||||
"authentik_used_by_shadows",
|
"authentik_used_by_shadows",
|
||||||
# List fields for which changes are not logged (due to them having dedicated objects)
|
|
||||||
# for example user's password and last_login
|
|
||||||
"authentik_signals_ignored_fields",
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
GROUP_RECURSION_LIMIT = 20
|
||||||
|
|
||||||
def default_token_duration():
|
|
||||||
|
def default_token_duration() -> datetime:
|
||||||
"""Default duration a Token is valid"""
|
"""Default duration a Token is valid"""
|
||||||
return now() + timedelta(minutes=30)
|
current_tenant = get_current_tenant()
|
||||||
|
token_duration = (
|
||||||
|
current_tenant.default_token_duration
|
||||||
|
if hasattr(current_tenant, "default_token_duration")
|
||||||
|
else DEFAULT_TOKEN_DURATION
|
||||||
|
)
|
||||||
|
return now() + timedelta_from_string(token_duration)
|
||||||
|
|
||||||
|
|
||||||
def default_token_key():
|
def default_token_key() -> str:
|
||||||
"""Default token key"""
|
"""Default token key"""
|
||||||
|
current_tenant = get_current_tenant()
|
||||||
|
token_length = (
|
||||||
|
current_tenant.default_token_length
|
||||||
|
if hasattr(current_tenant, "default_token_length")
|
||||||
|
else DEFAULT_TOKEN_LENGTH
|
||||||
|
)
|
||||||
# We use generate_id since the chars in the key should be easy
|
# We use generate_id since the chars in the key should be easy
|
||||||
# to use in Emails (for verification) and URLs (for recovery)
|
# to use in Emails (for verification) and URLs (for recovery)
|
||||||
return generate_id(CONFIG.get_int("default_token_length"))
|
return generate_id(token_length)
|
||||||
|
|
||||||
|
|
||||||
class UserTypes(models.TextChoices):
|
class UserTypes(models.TextChoices):
|
||||||
@ -86,6 +100,40 @@ class UserTypes(models.TextChoices):
|
|||||||
INTERNAL_SERVICE_ACCOUNT = "internal_service_account"
|
INTERNAL_SERVICE_ACCOUNT = "internal_service_account"
|
||||||
|
|
||||||
|
|
||||||
|
class GroupQuerySet(CTEQuerySet):
|
||||||
|
def with_children_recursive(self):
|
||||||
|
"""Recursively get all groups that have the current queryset as parents
|
||||||
|
or are indirectly related."""
|
||||||
|
|
||||||
|
def make_cte(cte):
|
||||||
|
"""Build the query that ends up in WITH RECURSIVE"""
|
||||||
|
# Start from self, aka the current query
|
||||||
|
# Add a depth attribute to limit the recursion
|
||||||
|
return self.annotate(
|
||||||
|
relative_depth=models.Value(0, output_field=models.IntegerField())
|
||||||
|
).union(
|
||||||
|
# Here is the recursive part of the query. cte refers to the previous iteration
|
||||||
|
# Only select groups for which the parent is part of the previous iteration
|
||||||
|
# and increase the depth
|
||||||
|
# Finally, limit the depth
|
||||||
|
cte.join(Group, group_uuid=cte.col.parent_id)
|
||||||
|
.annotate(
|
||||||
|
relative_depth=models.ExpressionWrapper(
|
||||||
|
cte.col.relative_depth
|
||||||
|
+ models.Value(1, output_field=models.IntegerField()),
|
||||||
|
output_field=models.IntegerField(),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.filter(relative_depth__lt=GROUP_RECURSION_LIMIT),
|
||||||
|
all=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Build the recursive query, see above
|
||||||
|
cte = With.recursive(make_cte)
|
||||||
|
# Return the result, as a usable queryset for Group.
|
||||||
|
return cte.join(Group, group_uuid=cte.col.group_uuid).with_cte(cte)
|
||||||
|
|
||||||
|
|
||||||
class Group(SerializerModel):
|
class Group(SerializerModel):
|
||||||
"""Group model which supports a basic hierarchy and has attributes"""
|
"""Group model which supports a basic hierarchy and has attributes"""
|
||||||
|
|
||||||
@ -108,6 +156,8 @@ class Group(SerializerModel):
|
|||||||
)
|
)
|
||||||
attributes = models.JSONField(default=dict, blank=True)
|
attributes = models.JSONField(default=dict, blank=True)
|
||||||
|
|
||||||
|
objects = GroupQuerySet.as_manager()
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def serializer(self) -> Serializer:
|
def serializer(self) -> Serializer:
|
||||||
from authentik.core.api.groups import GroupSerializer
|
from authentik.core.api.groups import GroupSerializer
|
||||||
@ -126,36 +176,11 @@ class Group(SerializerModel):
|
|||||||
return user.all_groups().filter(group_uuid=self.group_uuid).exists()
|
return user.all_groups().filter(group_uuid=self.group_uuid).exists()
|
||||||
|
|
||||||
def children_recursive(self: Self | QuerySet["Group"]) -> QuerySet["Group"]:
|
def children_recursive(self: Self | QuerySet["Group"]) -> QuerySet["Group"]:
|
||||||
"""Recursively get all groups that have this as parent or are indirectly related"""
|
"""Compatibility layer for Group.objects.with_children_recursive()"""
|
||||||
direct_groups = []
|
qs = self
|
||||||
if isinstance(self, QuerySet):
|
if not isinstance(self, QuerySet):
|
||||||
direct_groups = list(x for x in self.all().values_list("pk", flat=True).iterator())
|
qs = Group.objects.filter(group_uuid=self.group_uuid)
|
||||||
else:
|
return qs.with_children_recursive()
|
||||||
direct_groups = [self.pk]
|
|
||||||
if len(direct_groups) < 1:
|
|
||||||
return Group.objects.none()
|
|
||||||
query = """
|
|
||||||
WITH RECURSIVE parents AS (
|
|
||||||
SELECT authentik_core_group.*, 0 AS relative_depth
|
|
||||||
FROM authentik_core_group
|
|
||||||
WHERE authentik_core_group.group_uuid = ANY(%s)
|
|
||||||
|
|
||||||
UNION ALL
|
|
||||||
|
|
||||||
SELECT authentik_core_group.*, parents.relative_depth + 1
|
|
||||||
FROM authentik_core_group, parents
|
|
||||||
WHERE (
|
|
||||||
authentik_core_group.group_uuid = parents.parent_id and
|
|
||||||
parents.relative_depth < 20
|
|
||||||
)
|
|
||||||
)
|
|
||||||
SELECT group_uuid
|
|
||||||
FROM parents
|
|
||||||
GROUP BY group_uuid, name
|
|
||||||
ORDER BY name;
|
|
||||||
"""
|
|
||||||
group_pks = [group.pk for group in Group.objects.raw(query, [direct_groups]).iterator()]
|
|
||||||
return Group.objects.filter(pk__in=group_pks)
|
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return f"Group {self.name}"
|
return f"Group {self.name}"
|
||||||
@ -167,8 +192,13 @@ class Group(SerializerModel):
|
|||||||
"parent",
|
"parent",
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
indexes = [models.Index(fields=["name"])]
|
||||||
verbose_name = _("Group")
|
verbose_name = _("Group")
|
||||||
verbose_name_plural = _("Groups")
|
verbose_name_plural = _("Groups")
|
||||||
|
permissions = [
|
||||||
|
("add_user_to_group", _("Add user to group")),
|
||||||
|
("remove_user_from_group", _("Remove user from group")),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
class UserQuerySet(models.QuerySet):
|
class UserQuerySet(models.QuerySet):
|
||||||
@ -217,10 +247,8 @@ class User(SerializerModel, GuardianUserMixin, AbstractUser):
|
|||||||
return User._meta.get_field("path").default
|
return User._meta.get_field("path").default
|
||||||
|
|
||||||
def all_groups(self) -> QuerySet[Group]:
|
def all_groups(self) -> QuerySet[Group]:
|
||||||
"""Recursively get all groups this user is a member of.
|
"""Recursively get all groups this user is a member of."""
|
||||||
At least one query is done to get the direct groups of the user, with groups
|
return self.ak_groups.all().with_children_recursive()
|
||||||
there are at most 3 queries done"""
|
|
||||||
return Group.children_recursive(self.ak_groups.all())
|
|
||||||
|
|
||||||
def group_attributes(self, request: HttpRequest | None = None) -> dict[str, Any]:
|
def group_attributes(self, request: HttpRequest | None = None) -> dict[str, Any]:
|
||||||
"""Get a dictionary containing the attributes from all groups the user belongs to,
|
"""Get a dictionary containing the attributes from all groups the user belongs to,
|
||||||
@ -276,7 +304,7 @@ class User(SerializerModel, GuardianUserMixin, AbstractUser):
|
|||||||
@property
|
@property
|
||||||
def uid(self) -> str:
|
def uid(self) -> str:
|
||||||
"""Generate a globally unique UID, based on the user ID and the hashed secret key"""
|
"""Generate a globally unique UID, based on the user ID and the hashed secret key"""
|
||||||
return sha256(f"{self.id}-{get_install_id()}".encode("ascii")).hexdigest()
|
return sha256(f"{self.id}-{get_unique_identifier()}".encode("ascii")).hexdigest()
|
||||||
|
|
||||||
def locale(self, request: HttpRequest | None = None) -> str:
|
def locale(self, request: HttpRequest | None = None) -> str:
|
||||||
"""Get the locale the user has configured"""
|
"""Get the locale the user has configured"""
|
||||||
@ -305,13 +333,12 @@ class User(SerializerModel, GuardianUserMixin, AbstractUser):
|
|||||||
("preview_user", _("Can preview user data sent to providers")),
|
("preview_user", _("Can preview user data sent to providers")),
|
||||||
("view_user_applications", _("View applications the user has access to")),
|
("view_user_applications", _("View applications the user has access to")),
|
||||||
]
|
]
|
||||||
authentik_signals_ignored_fields = [
|
indexes = [
|
||||||
# Logged by the events `password_set`
|
models.Index(fields=["last_login"]),
|
||||||
# the `password_set` action/signal doesn't currently convey which user
|
models.Index(fields=["password_change_date"]),
|
||||||
# initiated the password change, so for now we'll log two actions
|
models.Index(fields=["uuid"]),
|
||||||
# ("password", "password_change_date"),
|
models.Index(fields=["path"]),
|
||||||
# Logged by `login`
|
models.Index(fields=["type"]),
|
||||||
("last_login",),
|
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@ -363,6 +390,10 @@ class Provider(SerializerModel):
|
|||||||
Can return None for providers that are not URL-based"""
|
Can return None for providers that are not URL-based"""
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def icon_url(self) -> str | None:
|
||||||
|
return None
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def component(self) -> str:
|
def component(self) -> str:
|
||||||
"""Return component used to edit this object"""
|
"""Return component used to edit this object"""
|
||||||
@ -617,6 +648,9 @@ class UserSourceConnection(SerializerModel, CreatedUpdatedModel):
|
|||||||
"""Get serializer for this model"""
|
"""Get serializer for this model"""
|
||||||
raise NotImplementedError
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return f"User-source connection (user={self.user_id}, source={self.source_id})"
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
unique_together = (("user", "source"),)
|
unique_together = (("user", "source"),)
|
||||||
|
|
||||||
@ -624,7 +658,7 @@ class UserSourceConnection(SerializerModel, CreatedUpdatedModel):
|
|||||||
class ExpiringModel(models.Model):
|
class ExpiringModel(models.Model):
|
||||||
"""Base Model which can expire, and is automatically cleaned up."""
|
"""Base Model which can expire, and is automatically cleaned up."""
|
||||||
|
|
||||||
expires = models.DateTimeField(default=default_token_duration)
|
expires = models.DateTimeField(default=None, null=True)
|
||||||
expiring = models.BooleanField(default=True)
|
expiring = models.BooleanField(default=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
@ -638,7 +672,7 @@ class ExpiringModel(models.Model):
|
|||||||
return self.delete(*args, **kwargs)
|
return self.delete(*args, **kwargs)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def filter_not_expired(cls, **kwargs) -> QuerySet:
|
def filter_not_expired(cls, **kwargs) -> QuerySet["Token"]:
|
||||||
"""Filer for tokens which are not expired yet or are not expiring,
|
"""Filer for tokens which are not expired yet or are not expiring,
|
||||||
and match filters in `kwargs`"""
|
and match filters in `kwargs`"""
|
||||||
for obj in cls.objects.filter(**kwargs).filter(Q(expires__lt=now(), expiring=True)):
|
for obj in cls.objects.filter(**kwargs).filter(Q(expires__lt=now(), expiring=True)):
|
||||||
@ -750,8 +784,10 @@ class PropertyMapping(SerializerModel, ManagedModel):
|
|||||||
evaluator = PropertyMappingEvaluator(self, user, request, **kwargs)
|
evaluator = PropertyMappingEvaluator(self, user, request, **kwargs)
|
||||||
try:
|
try:
|
||||||
return evaluator.evaluate(self.expression)
|
return evaluator.evaluate(self.expression)
|
||||||
|
except ControlFlowException as exc:
|
||||||
|
raise exc
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
raise PropertyMappingExpressionException(exc) from exc
|
raise PropertyMappingExpressionException(self, exc) from exc
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return f"Property Mapping {self.name}"
|
return f"Property Mapping {self.name}"
|
||||||
|
@ -10,7 +10,14 @@ from django.dispatch import receiver
|
|||||||
from django.http.request import HttpRequest
|
from django.http.request import HttpRequest
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik.core.models import Application, AuthenticatedSession, BackchannelProvider, User
|
from authentik.core.models import (
|
||||||
|
Application,
|
||||||
|
AuthenticatedSession,
|
||||||
|
BackchannelProvider,
|
||||||
|
ExpiringModel,
|
||||||
|
User,
|
||||||
|
default_token_duration,
|
||||||
|
)
|
||||||
|
|
||||||
# Arguments: user: User, password: str
|
# Arguments: user: User, password: str
|
||||||
password_changed = Signal()
|
password_changed = Signal()
|
||||||
@ -61,3 +68,12 @@ def backchannel_provider_pre_save(sender: type[Model], instance: Model, **_):
|
|||||||
if not isinstance(instance, BackchannelProvider):
|
if not isinstance(instance, BackchannelProvider):
|
||||||
return
|
return
|
||||||
instance.is_backchannel = True
|
instance.is_backchannel = True
|
||||||
|
|
||||||
|
|
||||||
|
@receiver(pre_save)
|
||||||
|
def expiring_model_pre_save(sender: type[Model], instance: Model, **_):
|
||||||
|
"""Ensure expires is set on ExpiringModels that are set to expire"""
|
||||||
|
if not issubclass(sender, ExpiringModel):
|
||||||
|
return
|
||||||
|
if instance.expiring and instance.expires is None:
|
||||||
|
instance.expires = default_token_duration()
|
||||||
|
@ -13,11 +13,12 @@ from django.utils.translation import gettext as _
|
|||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik.core.models import Source, SourceUserMatchingModes, User, UserSourceConnection
|
from authentik.core.models import Source, SourceUserMatchingModes, User, UserSourceConnection
|
||||||
from authentik.core.sources.stage import PLAN_CONTEXT_SOURCES_CONNECTION, PostUserEnrollmentStage
|
from authentik.core.sources.stage import PLAN_CONTEXT_SOURCES_CONNECTION, PostSourceStage
|
||||||
from authentik.events.models import Event, EventAction
|
from authentik.events.models import Event, EventAction
|
||||||
from authentik.flows.exceptions import FlowNonApplicableException
|
from authentik.flows.exceptions import FlowNonApplicableException
|
||||||
from authentik.flows.models import Flow, Stage, in_memory_stage
|
from authentik.flows.models import Flow, FlowToken, Stage, in_memory_stage
|
||||||
from authentik.flows.planner import (
|
from authentik.flows.planner import (
|
||||||
|
PLAN_CONTEXT_IS_RESTORED,
|
||||||
PLAN_CONTEXT_PENDING_USER,
|
PLAN_CONTEXT_PENDING_USER,
|
||||||
PLAN_CONTEXT_REDIRECT,
|
PLAN_CONTEXT_REDIRECT,
|
||||||
PLAN_CONTEXT_SOURCE,
|
PLAN_CONTEXT_SOURCE,
|
||||||
@ -35,6 +36,8 @@ from authentik.stages.password.stage import PLAN_CONTEXT_AUTHENTICATION_BACKEND
|
|||||||
from authentik.stages.prompt.stage import PLAN_CONTEXT_PROMPT
|
from authentik.stages.prompt.stage import PLAN_CONTEXT_PROMPT
|
||||||
from authentik.stages.user_write.stage import PLAN_CONTEXT_USER_PATH
|
from authentik.stages.user_write.stage import PLAN_CONTEXT_USER_PATH
|
||||||
|
|
||||||
|
SESSION_KEY_OVERRIDE_FLOW_TOKEN = "authentik/flows/source_override_flow_token" # nosec
|
||||||
|
|
||||||
|
|
||||||
class Action(Enum):
|
class Action(Enum):
|
||||||
"""Actions that can be decided based on the request
|
"""Actions that can be decided based on the request
|
||||||
@ -97,8 +100,6 @@ class SourceFlowManager:
|
|||||||
if self.request.user.is_authenticated:
|
if self.request.user.is_authenticated:
|
||||||
new_connection.user = self.request.user
|
new_connection.user = self.request.user
|
||||||
new_connection = self.update_connection(new_connection, **kwargs)
|
new_connection = self.update_connection(new_connection, **kwargs)
|
||||||
|
|
||||||
new_connection.save()
|
|
||||||
return Action.LINK, new_connection
|
return Action.LINK, new_connection
|
||||||
|
|
||||||
existing_connections = self.connection_type.objects.filter(
|
existing_connections = self.connection_type.objects.filter(
|
||||||
@ -145,7 +146,6 @@ class SourceFlowManager:
|
|||||||
]:
|
]:
|
||||||
new_connection.user = user
|
new_connection.user = user
|
||||||
new_connection = self.update_connection(new_connection, **kwargs)
|
new_connection = self.update_connection(new_connection, **kwargs)
|
||||||
new_connection.save()
|
|
||||||
return Action.LINK, new_connection
|
return Action.LINK, new_connection
|
||||||
if self.source.user_matching_mode in [
|
if self.source.user_matching_mode in [
|
||||||
SourceUserMatchingModes.EMAIL_DENY,
|
SourceUserMatchingModes.EMAIL_DENY,
|
||||||
@ -206,38 +206,55 @@ class SourceFlowManager:
|
|||||||
|
|
||||||
def get_stages_to_append(self, flow: Flow) -> list[Stage]:
|
def get_stages_to_append(self, flow: Flow) -> list[Stage]:
|
||||||
"""Hook to override stages which are appended to the flow"""
|
"""Hook to override stages which are appended to the flow"""
|
||||||
if not self.source.enrollment_flow:
|
return [
|
||||||
return []
|
in_memory_stage(PostSourceStage),
|
||||||
if flow.slug == self.source.enrollment_flow.slug:
|
]
|
||||||
return [
|
|
||||||
in_memory_stage(PostUserEnrollmentStage),
|
|
||||||
]
|
|
||||||
return []
|
|
||||||
|
|
||||||
def _prepare_flow(
|
def _prepare_flow(
|
||||||
self,
|
self,
|
||||||
flow: Flow,
|
flow: Flow | None,
|
||||||
connection: UserSourceConnection,
|
connection: UserSourceConnection,
|
||||||
stages: list[StageView] | None = None,
|
stages: list[StageView] | None = None,
|
||||||
**kwargs,
|
**kwargs,
|
||||||
) -> HttpResponse:
|
) -> HttpResponse:
|
||||||
"""Prepare Authentication Plan, redirect user FlowExecutor"""
|
"""Prepare Authentication Plan, redirect user FlowExecutor"""
|
||||||
# Ensure redirect is carried through when user was trying to
|
|
||||||
# authorize application
|
|
||||||
final_redirect = self.request.session.get(SESSION_KEY_GET, {}).get(
|
|
||||||
NEXT_ARG_NAME, "authentik_core:if-user"
|
|
||||||
)
|
|
||||||
kwargs.update(
|
kwargs.update(
|
||||||
{
|
{
|
||||||
# Since we authenticate the user by their token, they have no backend set
|
# Since we authenticate the user by their token, they have no backend set
|
||||||
PLAN_CONTEXT_AUTHENTICATION_BACKEND: BACKEND_INBUILT,
|
PLAN_CONTEXT_AUTHENTICATION_BACKEND: BACKEND_INBUILT,
|
||||||
PLAN_CONTEXT_SSO: True,
|
PLAN_CONTEXT_SSO: True,
|
||||||
PLAN_CONTEXT_SOURCE: self.source,
|
PLAN_CONTEXT_SOURCE: self.source,
|
||||||
PLAN_CONTEXT_REDIRECT: final_redirect,
|
|
||||||
PLAN_CONTEXT_SOURCES_CONNECTION: connection,
|
PLAN_CONTEXT_SOURCES_CONNECTION: connection,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
kwargs.update(self.policy_context)
|
kwargs.update(self.policy_context)
|
||||||
|
if SESSION_KEY_OVERRIDE_FLOW_TOKEN in self.request.session:
|
||||||
|
token: FlowToken = self.request.session.get(SESSION_KEY_OVERRIDE_FLOW_TOKEN)
|
||||||
|
self._logger.info("Replacing source flow with overridden flow", flow=token.flow.slug)
|
||||||
|
plan = token.plan
|
||||||
|
plan.context[PLAN_CONTEXT_IS_RESTORED] = token
|
||||||
|
plan.context.update(kwargs)
|
||||||
|
for stage in self.get_stages_to_append(flow):
|
||||||
|
plan.append_stage(stage)
|
||||||
|
if stages:
|
||||||
|
for stage in stages:
|
||||||
|
plan.append_stage(stage)
|
||||||
|
self.request.session[SESSION_KEY_PLAN] = plan
|
||||||
|
flow_slug = token.flow.slug
|
||||||
|
token.delete()
|
||||||
|
return redirect_with_qs(
|
||||||
|
"authentik_core:if-flow",
|
||||||
|
self.request.GET,
|
||||||
|
flow_slug=flow_slug,
|
||||||
|
)
|
||||||
|
# Ensure redirect is carried through when user was trying to
|
||||||
|
# authorize application
|
||||||
|
final_redirect = self.request.session.get(SESSION_KEY_GET, {}).get(
|
||||||
|
NEXT_ARG_NAME, "authentik_core:if-user"
|
||||||
|
)
|
||||||
|
if PLAN_CONTEXT_REDIRECT not in kwargs:
|
||||||
|
kwargs[PLAN_CONTEXT_REDIRECT] = final_redirect
|
||||||
|
|
||||||
if not flow:
|
if not flow:
|
||||||
return bad_request_message(
|
return bad_request_message(
|
||||||
self.request,
|
self.request,
|
||||||
@ -245,6 +262,9 @@ class SourceFlowManager:
|
|||||||
)
|
)
|
||||||
# We run the Flow planner here so we can pass the Pending user in the context
|
# We run the Flow planner here so we can pass the Pending user in the context
|
||||||
planner = FlowPlanner(flow)
|
planner = FlowPlanner(flow)
|
||||||
|
# We append some stages so the initial flow we get might be empty
|
||||||
|
planner.allow_empty_flows = True
|
||||||
|
planner.use_cache = False
|
||||||
plan = planner.plan(self.request, kwargs)
|
plan = planner.plan(self.request, kwargs)
|
||||||
for stage in self.get_stages_to_append(flow):
|
for stage in self.get_stages_to_append(flow):
|
||||||
plan.append_stage(stage)
|
plan.append_stage(stage)
|
||||||
@ -289,7 +309,9 @@ class SourceFlowManager:
|
|||||||
# When request isn't authenticated we jump straight to auth
|
# When request isn't authenticated we jump straight to auth
|
||||||
if not self.request.user.is_authenticated:
|
if not self.request.user.is_authenticated:
|
||||||
return self.handle_auth(connection)
|
return self.handle_auth(connection)
|
||||||
# Connection has already been saved
|
if SESSION_KEY_OVERRIDE_FLOW_TOKEN in self.request.session:
|
||||||
|
return self._prepare_flow(None, connection)
|
||||||
|
connection.save()
|
||||||
Event.new(
|
Event.new(
|
||||||
EventAction.SOURCE_LINKED,
|
EventAction.SOURCE_LINKED,
|
||||||
message="Linked Source",
|
message="Linked Source",
|
||||||
@ -303,7 +325,7 @@ class SourceFlowManager:
|
|||||||
reverse(
|
reverse(
|
||||||
"authentik_core:if-user",
|
"authentik_core:if-user",
|
||||||
)
|
)
|
||||||
+ f"#/settings;page-{self.source.slug}"
|
+ "#/settings;page-sources"
|
||||||
)
|
)
|
||||||
|
|
||||||
def handle_enroll(
|
def handle_enroll(
|
||||||
|
@ -10,7 +10,7 @@ from authentik.flows.stage import StageView
|
|||||||
PLAN_CONTEXT_SOURCES_CONNECTION = "goauthentik.io/sources/connection"
|
PLAN_CONTEXT_SOURCES_CONNECTION = "goauthentik.io/sources/connection"
|
||||||
|
|
||||||
|
|
||||||
class PostUserEnrollmentStage(StageView):
|
class PostSourceStage(StageView):
|
||||||
"""Dynamically injected stage which saves the Connection after
|
"""Dynamically injected stage which saves the Connection after
|
||||||
the user has been enrolled."""
|
the user has been enrolled."""
|
||||||
|
|
||||||
@ -21,10 +21,12 @@ class PostUserEnrollmentStage(StageView):
|
|||||||
]
|
]
|
||||||
user: User = self.executor.plan.context[PLAN_CONTEXT_PENDING_USER]
|
user: User = self.executor.plan.context[PLAN_CONTEXT_PENDING_USER]
|
||||||
connection.user = user
|
connection.user = user
|
||||||
|
linked = connection.pk is None
|
||||||
connection.save()
|
connection.save()
|
||||||
Event.new(
|
if linked:
|
||||||
EventAction.SOURCE_LINKED,
|
Event.new(
|
||||||
message="Linked Source",
|
EventAction.SOURCE_LINKED,
|
||||||
source=connection.source,
|
message="Linked Source",
|
||||||
).from_http(self.request)
|
source=connection.source,
|
||||||
|
).from_http(self.request)
|
||||||
return self.executor.stage_ok()
|
return self.executor.stage_ok()
|
||||||
|
@ -2,7 +2,9 @@
|
|||||||
|
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
from django.conf import ImproperlyConfigured
|
||||||
from django.contrib.sessions.backends.cache import KEY_PREFIX
|
from django.contrib.sessions.backends.cache import KEY_PREFIX
|
||||||
|
from django.contrib.sessions.backends.db import SessionStore as DBSessionStore
|
||||||
from django.core.cache import cache
|
from django.core.cache import cache
|
||||||
from django.utils.timezone import now
|
from django.utils.timezone import now
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
@ -15,6 +17,7 @@ from authentik.core.models import (
|
|||||||
User,
|
User,
|
||||||
)
|
)
|
||||||
from authentik.events.system_tasks import SystemTask, TaskStatus, prefill_task
|
from authentik.events.system_tasks import SystemTask, TaskStatus, prefill_task
|
||||||
|
from authentik.lib.config import CONFIG
|
||||||
from authentik.root.celery import CELERY_APP
|
from authentik.root.celery import CELERY_APP
|
||||||
|
|
||||||
LOGGER = get_logger()
|
LOGGER = get_logger()
|
||||||
@ -39,16 +42,31 @@ def clean_expired_models(self: SystemTask):
|
|||||||
amount = 0
|
amount = 0
|
||||||
|
|
||||||
for session in AuthenticatedSession.objects.all():
|
for session in AuthenticatedSession.objects.all():
|
||||||
cache_key = f"{KEY_PREFIX}{session.session_key}"
|
match CONFIG.get("session_storage", "cache"):
|
||||||
value = None
|
case "cache":
|
||||||
try:
|
cache_key = f"{KEY_PREFIX}{session.session_key}"
|
||||||
value = cache.get(cache_key)
|
value = None
|
||||||
|
try:
|
||||||
|
value = cache.get(cache_key)
|
||||||
|
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
LOGGER.debug("Failed to get session from cache", exc=exc)
|
LOGGER.debug("Failed to get session from cache", exc=exc)
|
||||||
if not value:
|
if not value:
|
||||||
session.delete()
|
session.delete()
|
||||||
amount += 1
|
amount += 1
|
||||||
|
case "db":
|
||||||
|
if not (
|
||||||
|
DBSessionStore.get_model_class()
|
||||||
|
.objects.filter(session_key=session.session_key, expire_date__gt=now())
|
||||||
|
.exists()
|
||||||
|
):
|
||||||
|
session.delete()
|
||||||
|
amount += 1
|
||||||
|
case _:
|
||||||
|
# Should never happen, as we check for other values in authentik/root/settings.py
|
||||||
|
raise ImproperlyConfigured(
|
||||||
|
"Invalid session_storage setting, allowed values are db and cache"
|
||||||
|
)
|
||||||
LOGGER.debug("Expired sessions", model=AuthenticatedSession, amount=amount)
|
LOGGER.debug("Expired sessions", model=AuthenticatedSession, amount=amount)
|
||||||
|
|
||||||
messages.append(f"Expired {amount} {AuthenticatedSession._meta.verbose_name_plural}")
|
messages.append(f"Expired {amount} {AuthenticatedSession._meta.verbose_name_plural}")
|
||||||
|
@ -10,7 +10,7 @@
|
|||||||
versionSubdomain: "{{ version_subdomain }}",
|
versionSubdomain: "{{ version_subdomain }}",
|
||||||
build: "{{ build }}",
|
build: "{{ build }}",
|
||||||
};
|
};
|
||||||
window.addEventListener("DOMContentLoaded", () => {
|
window.addEventListener("DOMContentLoaded", function () {
|
||||||
{% for message in messages %}
|
{% for message in messages %}
|
||||||
window.dispatchEvent(
|
window.dispatchEvent(
|
||||||
new CustomEvent("ak-message", {
|
new CustomEvent("ak-message", {
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
{% load static %}
|
{% load static %}
|
||||||
{% load i18n %}
|
{% load i18n %}
|
||||||
|
{% load authentik_core %}
|
||||||
|
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
|
|
||||||
@ -14,8 +15,8 @@
|
|||||||
{% endblock %}
|
{% endblock %}
|
||||||
<link rel="stylesheet" type="text/css" href="{% static 'dist/authentik.css' %}">
|
<link rel="stylesheet" type="text/css" href="{% static 'dist/authentik.css' %}">
|
||||||
<link rel="stylesheet" type="text/css" href="{% static 'dist/custom.css' %}" data-inject>
|
<link rel="stylesheet" type="text/css" href="{% static 'dist/custom.css' %}" data-inject>
|
||||||
<script src="{% static 'dist/poly.js' %}?version={{ version }}" type="module"></script>
|
{% versioned_script "dist/poly-%v.js" %}
|
||||||
<script src="{% static 'dist/standalone/loading/index.js' %}?version={{ version }}" type="module"></script>
|
{% versioned_script "dist/standalone/loading/index-%v.js" %}
|
||||||
{% block head %}
|
{% block head %}
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
<meta name="sentry-trace" content="{{ sentry_trace }}" />
|
<meta name="sentry-trace" content="{{ sentry_trace }}" />
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
{% extends "base/skeleton.html" %}
|
{% extends "base/skeleton.html" %}
|
||||||
|
|
||||||
{% load static %}
|
{% load authentik_core %}
|
||||||
|
|
||||||
{% block head %}
|
{% block head %}
|
||||||
<script src="{% static 'dist/admin/AdminInterface.js' %}?version={{ version }}" type="module"></script>
|
{% versioned_script "dist/admin/AdminInterface-%v.js" %}
|
||||||
<meta name="theme-color" content="#18191a" media="(prefers-color-scheme: dark)">
|
<meta name="theme-color" content="#18191a" media="(prefers-color-scheme: dark)">
|
||||||
<meta name="theme-color" content="#ffffff" media="(prefers-color-scheme: light)">
|
<meta name="theme-color" content="#ffffff" media="(prefers-color-scheme: light)">
|
||||||
{% include "base/header_js.html" %}
|
{% include "base/header_js.html" %}
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
{% extends "base/skeleton.html" %}
|
{% extends "base/skeleton.html" %}
|
||||||
|
|
||||||
{% load static %}
|
{% load authentik_core %}
|
||||||
|
|
||||||
{% block head %}
|
{% block head %}
|
||||||
<script src="{% static 'dist/user/UserInterface.js' %}?version={{ version }}" type="module"></script>
|
{% versioned_script "dist/user/UserInterface-%v.js" %}
|
||||||
<meta name="theme-color" content="#1c1e21" media="(prefers-color-scheme: light)">
|
<meta name="theme-color" content="#1c1e21" media="(prefers-color-scheme: light)">
|
||||||
<meta name="theme-color" content="#1c1e21" media="(prefers-color-scheme: dark)">
|
<meta name="theme-color" content="#1c1e21" media="(prefers-color-scheme: dark)">
|
||||||
{% include "base/header_js.html" %}
|
{% include "base/header_js.html" %}
|
||||||
|
@ -71,9 +71,9 @@
|
|||||||
</li>
|
</li>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
<li>
|
<li>
|
||||||
<a href="https://goauthentik.io?utm_source=authentik">
|
<span>
|
||||||
{% trans 'Powered by authentik' %}
|
{% trans 'Powered by authentik' %}
|
||||||
</a>
|
</span>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</footer>
|
</footer>
|
||||||
|
21
authentik/core/templatetags/authentik_core.py
Normal file
21
authentik/core/templatetags/authentik_core.py
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
"""authentik core tags"""
|
||||||
|
|
||||||
|
from django import template
|
||||||
|
from django.templatetags.static import static as static_loader
|
||||||
|
from django.utils.safestring import mark_safe
|
||||||
|
|
||||||
|
from authentik import get_full_version
|
||||||
|
|
||||||
|
register = template.Library()
|
||||||
|
|
||||||
|
|
||||||
|
@register.simple_tag()
|
||||||
|
def versioned_script(path: str) -> str:
|
||||||
|
"""Wrapper around {% static %} tag that supports setting the version"""
|
||||||
|
returned_lines = [
|
||||||
|
(
|
||||||
|
f'<script src="{static_loader(path.replace("%v", get_full_version()))}'
|
||||||
|
'" type="module"></script>'
|
||||||
|
),
|
||||||
|
]
|
||||||
|
return mark_safe("".join(returned_lines)) # nosec
|
@ -1,10 +1,11 @@
|
|||||||
"""Test Groups API"""
|
"""Test Groups API"""
|
||||||
|
|
||||||
from django.urls.base import reverse
|
from django.urls.base import reverse
|
||||||
|
from guardian.shortcuts import assign_perm
|
||||||
from rest_framework.test import APITestCase
|
from rest_framework.test import APITestCase
|
||||||
|
|
||||||
from authentik.core.models import Group, User
|
from authentik.core.models import Group, User
|
||||||
from authentik.core.tests.utils import create_test_admin_user
|
from authentik.core.tests.utils import create_test_admin_user, create_test_user
|
||||||
from authentik.lib.generators import generate_id
|
from authentik.lib.generators import generate_id
|
||||||
|
|
||||||
|
|
||||||
@ -12,13 +13,33 @@ class TestGroupsAPI(APITestCase):
|
|||||||
"""Test Groups API"""
|
"""Test Groups API"""
|
||||||
|
|
||||||
def setUp(self) -> None:
|
def setUp(self) -> None:
|
||||||
self.admin = create_test_admin_user()
|
self.login_user = create_test_user()
|
||||||
self.user = User.objects.create(username="test-user")
|
self.user = User.objects.create(username="test-user")
|
||||||
|
|
||||||
|
def test_list_with_users(self):
|
||||||
|
"""Test listing with users"""
|
||||||
|
admin = create_test_admin_user()
|
||||||
|
self.client.force_login(admin)
|
||||||
|
response = self.client.get(reverse("authentik_api:group-list"), {"include_users": "true"})
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
|
||||||
|
def test_retrieve_with_users(self):
|
||||||
|
"""Test retrieve with users"""
|
||||||
|
admin = create_test_admin_user()
|
||||||
|
group = Group.objects.create(name=generate_id())
|
||||||
|
self.client.force_login(admin)
|
||||||
|
response = self.client.get(
|
||||||
|
reverse("authentik_api:group-detail", kwargs={"pk": group.pk}),
|
||||||
|
{"include_users": "true"},
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
|
||||||
def test_add_user(self):
|
def test_add_user(self):
|
||||||
"""Test add_user"""
|
"""Test add_user"""
|
||||||
group = Group.objects.create(name=generate_id())
|
group = Group.objects.create(name=generate_id())
|
||||||
self.client.force_login(self.admin)
|
assign_perm("authentik_core.add_user_to_group", self.login_user, group)
|
||||||
|
assign_perm("authentik_core.view_user", self.login_user)
|
||||||
|
self.client.force_login(self.login_user)
|
||||||
res = self.client.post(
|
res = self.client.post(
|
||||||
reverse("authentik_api:group-add-user", kwargs={"pk": group.pk}),
|
reverse("authentik_api:group-add-user", kwargs={"pk": group.pk}),
|
||||||
data={
|
data={
|
||||||
@ -32,7 +53,9 @@ class TestGroupsAPI(APITestCase):
|
|||||||
def test_add_user_404(self):
|
def test_add_user_404(self):
|
||||||
"""Test add_user"""
|
"""Test add_user"""
|
||||||
group = Group.objects.create(name=generate_id())
|
group = Group.objects.create(name=generate_id())
|
||||||
self.client.force_login(self.admin)
|
assign_perm("authentik_core.add_user_to_group", self.login_user, group)
|
||||||
|
assign_perm("authentik_core.view_user", self.login_user)
|
||||||
|
self.client.force_login(self.login_user)
|
||||||
res = self.client.post(
|
res = self.client.post(
|
||||||
reverse("authentik_api:group-add-user", kwargs={"pk": group.pk}),
|
reverse("authentik_api:group-add-user", kwargs={"pk": group.pk}),
|
||||||
data={
|
data={
|
||||||
@ -44,8 +67,10 @@ class TestGroupsAPI(APITestCase):
|
|||||||
def test_remove_user(self):
|
def test_remove_user(self):
|
||||||
"""Test remove_user"""
|
"""Test remove_user"""
|
||||||
group = Group.objects.create(name=generate_id())
|
group = Group.objects.create(name=generate_id())
|
||||||
|
assign_perm("authentik_core.remove_user_from_group", self.login_user, group)
|
||||||
|
assign_perm("authentik_core.view_user", self.login_user)
|
||||||
group.users.add(self.user)
|
group.users.add(self.user)
|
||||||
self.client.force_login(self.admin)
|
self.client.force_login(self.login_user)
|
||||||
res = self.client.post(
|
res = self.client.post(
|
||||||
reverse("authentik_api:group-remove-user", kwargs={"pk": group.pk}),
|
reverse("authentik_api:group-remove-user", kwargs={"pk": group.pk}),
|
||||||
data={
|
data={
|
||||||
@ -59,8 +84,10 @@ class TestGroupsAPI(APITestCase):
|
|||||||
def test_remove_user_404(self):
|
def test_remove_user_404(self):
|
||||||
"""Test remove_user"""
|
"""Test remove_user"""
|
||||||
group = Group.objects.create(name=generate_id())
|
group = Group.objects.create(name=generate_id())
|
||||||
|
assign_perm("authentik_core.remove_user_from_group", self.login_user, group)
|
||||||
|
assign_perm("authentik_core.view_user", self.login_user)
|
||||||
group.users.add(self.user)
|
group.users.add(self.user)
|
||||||
self.client.force_login(self.admin)
|
self.client.force_login(self.login_user)
|
||||||
res = self.client.post(
|
res = self.client.post(
|
||||||
reverse("authentik_api:group-remove-user", kwargs={"pk": group.pk}),
|
reverse("authentik_api:group-remove-user", kwargs={"pk": group.pk}),
|
||||||
data={
|
data={
|
||||||
@ -72,11 +99,12 @@ class TestGroupsAPI(APITestCase):
|
|||||||
def test_parent_self(self):
|
def test_parent_self(self):
|
||||||
"""Test parent"""
|
"""Test parent"""
|
||||||
group = Group.objects.create(name=generate_id())
|
group = Group.objects.create(name=generate_id())
|
||||||
self.client.force_login(self.admin)
|
assign_perm("view_group", self.login_user, group)
|
||||||
|
assign_perm("change_group", self.login_user, group)
|
||||||
|
self.client.force_login(self.login_user)
|
||||||
res = self.client.patch(
|
res = self.client.patch(
|
||||||
reverse("authentik_api:group-detail", kwargs={"pk": group.pk}),
|
reverse("authentik_api:group-detail", kwargs={"pk": group.pk}),
|
||||||
data={
|
data={
|
||||||
"pk": self.user.pk + 3,
|
|
||||||
"parent": group.pk,
|
"parent": group.pk,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
@ -1,14 +1,14 @@
|
|||||||
"""authentik core models tests"""
|
"""authentik core models tests"""
|
||||||
|
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
from time import sleep
|
from datetime import timedelta
|
||||||
|
|
||||||
from django.test import RequestFactory, TestCase
|
from django.test import RequestFactory, TestCase
|
||||||
from django.utils.timezone import now
|
from django.utils.timezone import now
|
||||||
|
from freezegun import freeze_time
|
||||||
from guardian.shortcuts import get_anonymous_user
|
from guardian.shortcuts import get_anonymous_user
|
||||||
|
|
||||||
from authentik.core.models import Provider, Source, Token
|
from authentik.core.models import Provider, Source, Token
|
||||||
from authentik.flows.models import Stage
|
|
||||||
from authentik.lib.utils.reflection import all_subclasses
|
from authentik.lib.utils.reflection import all_subclasses
|
||||||
|
|
||||||
|
|
||||||
@ -17,18 +17,20 @@ class TestModels(TestCase):
|
|||||||
|
|
||||||
def test_token_expire(self):
|
def test_token_expire(self):
|
||||||
"""Test token expiring"""
|
"""Test token expiring"""
|
||||||
token = Token.objects.create(expires=now(), user=get_anonymous_user())
|
with freeze_time() as freeze:
|
||||||
sleep(0.5)
|
token = Token.objects.create(expires=now(), user=get_anonymous_user())
|
||||||
self.assertTrue(token.is_expired)
|
freeze.tick(timedelta(seconds=1))
|
||||||
|
self.assertTrue(token.is_expired)
|
||||||
|
|
||||||
def test_token_expire_no_expire(self):
|
def test_token_expire_no_expire(self):
|
||||||
"""Test token expiring with "expiring" set"""
|
"""Test token expiring with "expiring" set"""
|
||||||
token = Token.objects.create(expires=now(), user=get_anonymous_user(), expiring=False)
|
with freeze_time() as freeze:
|
||||||
sleep(0.5)
|
token = Token.objects.create(expires=now(), user=get_anonymous_user(), expiring=False)
|
||||||
self.assertFalse(token.is_expired)
|
freeze.tick(timedelta(seconds=1))
|
||||||
|
self.assertFalse(token.is_expired)
|
||||||
|
|
||||||
|
|
||||||
def source_tester_factory(test_model: type[Stage]) -> Callable:
|
def source_tester_factory(test_model: type[Source]) -> Callable:
|
||||||
"""Test source"""
|
"""Test source"""
|
||||||
|
|
||||||
factory = RequestFactory()
|
factory = RequestFactory()
|
||||||
@ -36,19 +38,19 @@ def source_tester_factory(test_model: type[Stage]) -> Callable:
|
|||||||
|
|
||||||
def tester(self: TestModels):
|
def tester(self: TestModels):
|
||||||
model_class = None
|
model_class = None
|
||||||
if test_model._meta.abstract: # pragma: no cover
|
if test_model._meta.abstract:
|
||||||
model_class = test_model.__bases__[0]()
|
model_class = [x for x in test_model.__bases__ if issubclass(x, Source)][0]()
|
||||||
else:
|
else:
|
||||||
model_class = test_model()
|
model_class = test_model()
|
||||||
model_class.slug = "test"
|
model_class.slug = "test"
|
||||||
self.assertIsNotNone(model_class.component)
|
self.assertIsNotNone(model_class.component)
|
||||||
_ = model_class.ui_login_button(request)
|
model_class.ui_login_button(request)
|
||||||
_ = model_class.ui_user_settings()
|
model_class.ui_user_settings()
|
||||||
|
|
||||||
return tester
|
return tester
|
||||||
|
|
||||||
|
|
||||||
def provider_tester_factory(test_model: type[Stage]) -> Callable:
|
def provider_tester_factory(test_model: type[Provider]) -> Callable:
|
||||||
"""Test provider"""
|
"""Test provider"""
|
||||||
|
|
||||||
def tester(self: TestModels):
|
def tester(self: TestModels):
|
||||||
|
@ -3,7 +3,10 @@
|
|||||||
from django.test import RequestFactory, TestCase
|
from django.test import RequestFactory, TestCase
|
||||||
from guardian.shortcuts import get_anonymous_user
|
from guardian.shortcuts import get_anonymous_user
|
||||||
|
|
||||||
from authentik.core.exceptions import PropertyMappingExpressionException
|
from authentik.core.expression.exceptions import (
|
||||||
|
PropertyMappingExpressionException,
|
||||||
|
SkipObjectException,
|
||||||
|
)
|
||||||
from authentik.core.models import PropertyMapping
|
from authentik.core.models import PropertyMapping
|
||||||
from authentik.core.tests.utils import create_test_admin_user
|
from authentik.core.tests.utils import create_test_admin_user
|
||||||
from authentik.events.models import Event, EventAction
|
from authentik.events.models import Event, EventAction
|
||||||
@ -42,6 +45,17 @@ class TestPropertyMappings(TestCase):
|
|||||||
self.assertTrue(events.exists())
|
self.assertTrue(events.exists())
|
||||||
self.assertEqual(len(events), 1)
|
self.assertEqual(len(events), 1)
|
||||||
|
|
||||||
|
def test_expression_skip(self):
|
||||||
|
"""Test expression error"""
|
||||||
|
expr = "raise SkipObject"
|
||||||
|
mapping = PropertyMapping.objects.create(name=generate_id(), expression=expr)
|
||||||
|
with self.assertRaises(SkipObjectException):
|
||||||
|
mapping.evaluate(None, None)
|
||||||
|
events = Event.objects.filter(
|
||||||
|
action=EventAction.PROPERTY_MAPPING_EXCEPTION, context__expression=expr
|
||||||
|
)
|
||||||
|
self.assertFalse(events.exists())
|
||||||
|
|
||||||
def test_expression_error_extended(self):
|
def test_expression_error_extended(self):
|
||||||
"""Test expression error (with user and http request"""
|
"""Test expression error (with user and http request"""
|
||||||
expr = "return aaa"
|
expr = "return aaa"
|
||||||
@ -66,14 +80,11 @@ class TestPropertyMappings(TestCase):
|
|||||||
expression="return request.http_request.path",
|
expression="return request.http_request.path",
|
||||||
)
|
)
|
||||||
http_request = self.factory.get("/")
|
http_request = self.factory.get("/")
|
||||||
tmpl = (
|
tmpl = f"""
|
||||||
"""
|
res = ak_call_policy('{expr.name}')
|
||||||
res = ak_call_policy('%s')
|
|
||||||
result = [request.http_request.path, res.raw_result]
|
result = [request.http_request.path, res.raw_result]
|
||||||
return result
|
return result
|
||||||
"""
|
"""
|
||||||
% expr.name
|
|
||||||
)
|
|
||||||
evaluator = PropertyMapping(expression=tmpl, name=generate_id())
|
evaluator = PropertyMapping(expression=tmpl, name=generate_id())
|
||||||
res = evaluator.evaluate(self.user, http_request)
|
res = evaluator.evaluate(self.user, http_request)
|
||||||
self.assertEqual(res, ["/", "/"])
|
self.assertEqual(res, ["/", "/"])
|
||||||
|
@ -6,9 +6,10 @@ from django.urls import reverse
|
|||||||
from rest_framework.serializers import ValidationError
|
from rest_framework.serializers import ValidationError
|
||||||
from rest_framework.test import APITestCase
|
from rest_framework.test import APITestCase
|
||||||
|
|
||||||
from authentik.core.api.propertymappings import PropertyMappingSerializer
|
from authentik.core.api.property_mappings import PropertyMappingSerializer
|
||||||
from authentik.core.models import PropertyMapping
|
from authentik.core.models import Group, PropertyMapping
|
||||||
from authentik.core.tests.utils import create_test_admin_user
|
from authentik.core.tests.utils import create_test_admin_user
|
||||||
|
from authentik.lib.generators import generate_id
|
||||||
|
|
||||||
|
|
||||||
class TestPropertyMappingAPI(APITestCase):
|
class TestPropertyMappingAPI(APITestCase):
|
||||||
@ -16,23 +17,40 @@ class TestPropertyMappingAPI(APITestCase):
|
|||||||
|
|
||||||
def setUp(self) -> None:
|
def setUp(self) -> None:
|
||||||
super().setUp()
|
super().setUp()
|
||||||
self.mapping = PropertyMapping.objects.create(
|
|
||||||
name="dummy", expression="""return {'foo': 'bar'}"""
|
|
||||||
)
|
|
||||||
self.user = create_test_admin_user()
|
self.user = create_test_admin_user()
|
||||||
self.client.force_login(self.user)
|
self.client.force_login(self.user)
|
||||||
|
|
||||||
def test_test_call(self):
|
def test_test_call(self):
|
||||||
"""Test PropertMappings's test endpoint"""
|
"""Test PropertyMappings's test endpoint"""
|
||||||
|
mapping = PropertyMapping.objects.create(
|
||||||
|
name="dummy", expression="""return {'foo': 'bar', 'baz': user.username}"""
|
||||||
|
)
|
||||||
response = self.client.post(
|
response = self.client.post(
|
||||||
reverse("authentik_api:propertymapping-test", kwargs={"pk": self.mapping.pk}),
|
reverse("authentik_api:propertymapping-test", kwargs={"pk": mapping.pk}),
|
||||||
data={
|
data={
|
||||||
"user": self.user.pk,
|
"user": self.user.pk,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
self.assertJSONEqual(
|
self.assertJSONEqual(
|
||||||
response.content.decode(),
|
response.content.decode(),
|
||||||
{"result": dumps({"foo": "bar"}), "successful": True},
|
{"result": dumps({"foo": "bar", "baz": self.user.username}), "successful": True},
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_test_call_group(self):
|
||||||
|
"""Test PropertyMappings's test endpoint"""
|
||||||
|
mapping = PropertyMapping.objects.create(
|
||||||
|
name="dummy", expression="""return {'foo': 'bar', 'baz': group.name}"""
|
||||||
|
)
|
||||||
|
group = Group.objects.create(name=generate_id())
|
||||||
|
response = self.client.post(
|
||||||
|
reverse("authentik_api:propertymapping-test", kwargs={"pk": mapping.pk}),
|
||||||
|
data={
|
||||||
|
"group": group.pk,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
self.assertJSONEqual(
|
||||||
|
response.content.decode(),
|
||||||
|
{"result": dumps({"foo": "bar", "baz": group.name}), "successful": True},
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_validate(self):
|
def test_validate(self):
|
||||||
|
@ -2,11 +2,15 @@
|
|||||||
|
|
||||||
from django.contrib.auth.models import AnonymousUser
|
from django.contrib.auth.models import AnonymousUser
|
||||||
from django.test import TestCase
|
from django.test import TestCase
|
||||||
|
from django.urls import reverse
|
||||||
from guardian.utils import get_anonymous_user
|
from guardian.utils import get_anonymous_user
|
||||||
|
|
||||||
from authentik.core.models import SourceUserMatchingModes, User
|
from authentik.core.models import SourceUserMatchingModes, User
|
||||||
from authentik.core.sources.flow_manager import Action
|
from authentik.core.sources.flow_manager import Action
|
||||||
|
from authentik.core.sources.stage import PostSourceStage
|
||||||
from authentik.core.tests.utils import create_test_flow
|
from authentik.core.tests.utils import create_test_flow
|
||||||
|
from authentik.flows.planner import FlowPlan
|
||||||
|
from authentik.flows.views.executor import SESSION_KEY_PLAN
|
||||||
from authentik.lib.generators import generate_id
|
from authentik.lib.generators import generate_id
|
||||||
from authentik.lib.tests.utils import get_request
|
from authentik.lib.tests.utils import get_request
|
||||||
from authentik.policies.denied import AccessDeniedResponse
|
from authentik.policies.denied import AccessDeniedResponse
|
||||||
@ -21,42 +25,62 @@ class TestSourceFlowManager(TestCase):
|
|||||||
|
|
||||||
def setUp(self) -> None:
|
def setUp(self) -> None:
|
||||||
super().setUp()
|
super().setUp()
|
||||||
self.source: OAuthSource = OAuthSource.objects.create(name="test")
|
self.authentication_flow = create_test_flow()
|
||||||
|
self.enrollment_flow = create_test_flow()
|
||||||
|
self.source: OAuthSource = OAuthSource.objects.create(
|
||||||
|
name=generate_id(),
|
||||||
|
slug=generate_id(),
|
||||||
|
authentication_flow=self.authentication_flow,
|
||||||
|
enrollment_flow=self.enrollment_flow,
|
||||||
|
)
|
||||||
self.identifier = generate_id()
|
self.identifier = generate_id()
|
||||||
|
|
||||||
def test_unauthenticated_enroll(self):
|
def test_unauthenticated_enroll(self):
|
||||||
"""Test un-authenticated user enrolling"""
|
"""Test un-authenticated user enrolling"""
|
||||||
flow_manager = OAuthSourceFlowManager(
|
request = get_request("/", user=AnonymousUser())
|
||||||
self.source, get_request("/", user=AnonymousUser()), self.identifier, {}
|
flow_manager = OAuthSourceFlowManager(self.source, request, self.identifier, {})
|
||||||
)
|
|
||||||
action, _ = flow_manager.get_action()
|
action, _ = flow_manager.get_action()
|
||||||
self.assertEqual(action, Action.ENROLL)
|
self.assertEqual(action, Action.ENROLL)
|
||||||
flow_manager.get_flow()
|
response = flow_manager.get_flow()
|
||||||
|
self.assertEqual(response.status_code, 302)
|
||||||
|
flow_plan: FlowPlan = request.session[SESSION_KEY_PLAN]
|
||||||
|
self.assertEqual(flow_plan.bindings[0].stage.view, PostSourceStage)
|
||||||
|
|
||||||
def test_unauthenticated_auth(self):
|
def test_unauthenticated_auth(self):
|
||||||
"""Test un-authenticated user authenticating"""
|
"""Test un-authenticated user authenticating"""
|
||||||
UserOAuthSourceConnection.objects.create(
|
UserOAuthSourceConnection.objects.create(
|
||||||
user=get_anonymous_user(), source=self.source, identifier=self.identifier
|
user=get_anonymous_user(), source=self.source, identifier=self.identifier
|
||||||
)
|
)
|
||||||
|
request = get_request("/", user=AnonymousUser())
|
||||||
flow_manager = OAuthSourceFlowManager(
|
flow_manager = OAuthSourceFlowManager(self.source, request, self.identifier, {})
|
||||||
self.source, get_request("/", user=AnonymousUser()), self.identifier, {}
|
|
||||||
)
|
|
||||||
action, _ = flow_manager.get_action()
|
action, _ = flow_manager.get_action()
|
||||||
self.assertEqual(action, Action.AUTH)
|
self.assertEqual(action, Action.AUTH)
|
||||||
flow_manager.get_flow()
|
response = flow_manager.get_flow()
|
||||||
|
self.assertEqual(response.status_code, 302)
|
||||||
|
flow_plan: FlowPlan = request.session[SESSION_KEY_PLAN]
|
||||||
|
self.assertEqual(flow_plan.bindings[0].stage.view, PostSourceStage)
|
||||||
|
|
||||||
def test_authenticated_link(self):
|
def test_authenticated_link(self):
|
||||||
"""Test authenticated user linking"""
|
"""Test authenticated user linking"""
|
||||||
UserOAuthSourceConnection.objects.create(
|
|
||||||
user=get_anonymous_user(), source=self.source, identifier=self.identifier
|
|
||||||
)
|
|
||||||
user = User.objects.create(username="foo", email="foo@bar.baz")
|
user = User.objects.create(username="foo", email="foo@bar.baz")
|
||||||
flow_manager = OAuthSourceFlowManager(
|
request = get_request("/", user=user)
|
||||||
self.source, get_request("/", user=user), self.identifier, {}
|
flow_manager = OAuthSourceFlowManager(self.source, request, self.identifier, {})
|
||||||
)
|
action, connection = flow_manager.get_action()
|
||||||
action, _ = flow_manager.get_action()
|
|
||||||
self.assertEqual(action, Action.LINK)
|
self.assertEqual(action, Action.LINK)
|
||||||
|
self.assertIsNone(connection.pk)
|
||||||
|
response = flow_manager.get_flow()
|
||||||
|
self.assertEqual(response.status_code, 302)
|
||||||
|
self.assertEqual(
|
||||||
|
response.url,
|
||||||
|
reverse("authentik_core:if-user") + "#/settings;page-sources",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_unauthenticated_link(self):
|
||||||
|
"""Test un-authenticated user linking"""
|
||||||
|
flow_manager = OAuthSourceFlowManager(self.source, get_request("/"), self.identifier, {})
|
||||||
|
action, connection = flow_manager.get_action()
|
||||||
|
self.assertEqual(action, Action.LINK)
|
||||||
|
self.assertIsNone(connection.pk)
|
||||||
flow_manager.get_flow()
|
flow_manager.get_flow()
|
||||||
|
|
||||||
def test_unauthenticated_enroll_email(self):
|
def test_unauthenticated_enroll_email(self):
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
"""Test token API"""
|
"""Test token API"""
|
||||||
|
|
||||||
|
from datetime import datetime, timedelta
|
||||||
from json import loads
|
from json import loads
|
||||||
|
|
||||||
from django.urls.base import reverse
|
from django.urls.base import reverse
|
||||||
@ -7,8 +8,13 @@ from guardian.shortcuts import get_anonymous_user
|
|||||||
from rest_framework.test import APITestCase
|
from rest_framework.test import APITestCase
|
||||||
|
|
||||||
from authentik.core.api.tokens import TokenSerializer
|
from authentik.core.api.tokens import TokenSerializer
|
||||||
from authentik.core.models import USER_ATTRIBUTE_TOKEN_EXPIRING, Token, TokenIntents, User
|
from authentik.core.models import (
|
||||||
from authentik.core.tests.utils import create_test_admin_user
|
USER_ATTRIBUTE_TOKEN_EXPIRING,
|
||||||
|
USER_ATTRIBUTE_TOKEN_MAXIMUM_LIFETIME,
|
||||||
|
Token,
|
||||||
|
TokenIntents,
|
||||||
|
)
|
||||||
|
from authentik.core.tests.utils import create_test_admin_user, create_test_user
|
||||||
from authentik.lib.generators import generate_id
|
from authentik.lib.generators import generate_id
|
||||||
|
|
||||||
|
|
||||||
@ -17,7 +23,7 @@ class TestTokenAPI(APITestCase):
|
|||||||
|
|
||||||
def setUp(self) -> None:
|
def setUp(self) -> None:
|
||||||
super().setUp()
|
super().setUp()
|
||||||
self.user = User.objects.create(username="testuser")
|
self.user = create_test_user()
|
||||||
self.admin = create_test_admin_user()
|
self.admin = create_test_admin_user()
|
||||||
self.client.force_login(self.user)
|
self.client.force_login(self.user)
|
||||||
|
|
||||||
@ -76,6 +82,95 @@ class TestTokenAPI(APITestCase):
|
|||||||
self.assertEqual(token.intent, TokenIntents.INTENT_API)
|
self.assertEqual(token.intent, TokenIntents.INTENT_API)
|
||||||
self.assertEqual(token.expiring, False)
|
self.assertEqual(token.expiring, False)
|
||||||
|
|
||||||
|
def test_token_create_expiring(self):
|
||||||
|
"""Test token creation endpoint"""
|
||||||
|
self.user.attributes[USER_ATTRIBUTE_TOKEN_EXPIRING] = True
|
||||||
|
self.user.save()
|
||||||
|
response = self.client.post(
|
||||||
|
reverse("authentik_api:token-list"), {"identifier": "test-token"}
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 201)
|
||||||
|
token = Token.objects.get(identifier="test-token")
|
||||||
|
self.assertEqual(token.user, self.user)
|
||||||
|
self.assertEqual(token.intent, TokenIntents.INTENT_API)
|
||||||
|
self.assertEqual(token.expiring, True)
|
||||||
|
|
||||||
|
def test_token_create_expiring_custom_ok(self):
|
||||||
|
"""Test token creation endpoint"""
|
||||||
|
self.user.attributes[USER_ATTRIBUTE_TOKEN_EXPIRING] = True
|
||||||
|
self.user.attributes[USER_ATTRIBUTE_TOKEN_MAXIMUM_LIFETIME] = "hours=2"
|
||||||
|
self.user.save()
|
||||||
|
expires = datetime.now() + timedelta(hours=1)
|
||||||
|
response = self.client.post(
|
||||||
|
reverse("authentik_api:token-list"),
|
||||||
|
{
|
||||||
|
"identifier": "test-token",
|
||||||
|
"expires": expires,
|
||||||
|
"intent": TokenIntents.INTENT_APP_PASSWORD,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 201)
|
||||||
|
token = Token.objects.get(identifier="test-token")
|
||||||
|
self.assertEqual(token.user, self.user)
|
||||||
|
self.assertEqual(token.intent, TokenIntents.INTENT_APP_PASSWORD)
|
||||||
|
self.assertEqual(token.expiring, True)
|
||||||
|
self.assertEqual(token.expires.timestamp(), expires.timestamp())
|
||||||
|
|
||||||
|
def test_token_create_expiring_custom_nok(self):
|
||||||
|
"""Test token creation endpoint"""
|
||||||
|
self.user.attributes[USER_ATTRIBUTE_TOKEN_EXPIRING] = True
|
||||||
|
self.user.attributes[USER_ATTRIBUTE_TOKEN_MAXIMUM_LIFETIME] = "hours=2"
|
||||||
|
self.user.save()
|
||||||
|
expires = datetime.now() + timedelta(hours=3)
|
||||||
|
response = self.client.post(
|
||||||
|
reverse("authentik_api:token-list"),
|
||||||
|
{
|
||||||
|
"identifier": "test-token",
|
||||||
|
"expires": expires,
|
||||||
|
"intent": TokenIntents.INTENT_APP_PASSWORD,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 400)
|
||||||
|
|
||||||
|
def test_token_create_expiring_custom_api(self):
|
||||||
|
"""Test token creation endpoint"""
|
||||||
|
self.user.attributes[USER_ATTRIBUTE_TOKEN_EXPIRING] = True
|
||||||
|
self.user.attributes[USER_ATTRIBUTE_TOKEN_MAXIMUM_LIFETIME] = "hours=2"
|
||||||
|
self.user.save()
|
||||||
|
expires = datetime.now() + timedelta(seconds=3)
|
||||||
|
response = self.client.post(
|
||||||
|
reverse("authentik_api:token-list"),
|
||||||
|
{
|
||||||
|
"identifier": "test-token",
|
||||||
|
"expires": expires,
|
||||||
|
"intent": TokenIntents.INTENT_API,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 201)
|
||||||
|
token = Token.objects.get(identifier="test-token")
|
||||||
|
self.assertEqual(token.user, self.user)
|
||||||
|
self.assertEqual(token.intent, TokenIntents.INTENT_API)
|
||||||
|
self.assertEqual(token.expiring, True)
|
||||||
|
self.assertNotEqual(token.expires.timestamp(), expires.timestamp())
|
||||||
|
|
||||||
|
def test_token_change_user(self):
|
||||||
|
"""Test creating a token and then changing the user"""
|
||||||
|
ident = generate_id()
|
||||||
|
response = self.client.post(reverse("authentik_api:token-list"), {"identifier": ident})
|
||||||
|
self.assertEqual(response.status_code, 201)
|
||||||
|
token = Token.objects.get(identifier=ident)
|
||||||
|
self.assertEqual(token.user, self.user)
|
||||||
|
self.assertEqual(token.intent, TokenIntents.INTENT_API)
|
||||||
|
self.assertEqual(token.expiring, True)
|
||||||
|
self.assertTrue(self.user.has_perm("authentik_core.view_token_key", token))
|
||||||
|
response = self.client.put(
|
||||||
|
reverse("authentik_api:token-detail", kwargs={"identifier": ident}),
|
||||||
|
data={"identifier": "user_token_poc_v3", "intent": "api", "user": self.admin.pk},
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 400)
|
||||||
|
token.refresh_from_db()
|
||||||
|
self.assertEqual(token.user, self.user)
|
||||||
|
|
||||||
def test_list(self):
|
def test_list(self):
|
||||||
"""Test Token List (Test normal authentication)"""
|
"""Test Token List (Test normal authentication)"""
|
||||||
Token.objects.all().delete()
|
Token.objects.all().delete()
|
||||||
|
@ -41,6 +41,12 @@ class TestUsersAPI(APITestCase):
|
|||||||
)
|
)
|
||||||
self.assertEqual(response.status_code, 200)
|
self.assertEqual(response.status_code, 200)
|
||||||
|
|
||||||
|
def test_list_with_groups(self):
|
||||||
|
"""Test listing with groups"""
|
||||||
|
self.client.force_login(self.admin)
|
||||||
|
response = self.client.get(reverse("authentik_api:user-list"), {"include_groups": "true"})
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
|
||||||
def test_metrics(self):
|
def test_metrics(self):
|
||||||
"""Test user's metrics"""
|
"""Test user's metrics"""
|
||||||
self.client.force_login(self.admin)
|
self.client.force_login(self.admin)
|
||||||
|
@ -8,7 +8,6 @@ from rest_framework.test import APITestCase
|
|||||||
|
|
||||||
from authentik.core.models import User
|
from authentik.core.models import User
|
||||||
from authentik.core.tests.utils import create_test_admin_user
|
from authentik.core.tests.utils import create_test_admin_user
|
||||||
from authentik.lib.config import CONFIG
|
|
||||||
from authentik.tenants.utils import get_current_tenant
|
from authentik.tenants.utils import get_current_tenant
|
||||||
|
|
||||||
|
|
||||||
@ -25,7 +24,6 @@ class TestUsersAvatars(APITestCase):
|
|||||||
tenant.avatars = mode
|
tenant.avatars = mode
|
||||||
tenant.save()
|
tenant.save()
|
||||||
|
|
||||||
@CONFIG.patch("avatars", "none")
|
|
||||||
def test_avatars_none(self):
|
def test_avatars_none(self):
|
||||||
"""Test avatars none"""
|
"""Test avatars none"""
|
||||||
self.set_avatar_mode("none")
|
self.set_avatar_mode("none")
|
||||||
@ -44,8 +42,8 @@ class TestUsersAvatars(APITestCase):
|
|||||||
with Mocker() as mocker:
|
with Mocker() as mocker:
|
||||||
mocker.head(
|
mocker.head(
|
||||||
(
|
(
|
||||||
"https://secure.gravatar.com/avatar/84730f9c1851d1ea03f1a"
|
"https://www.gravatar.com/avatar/76eb3c74c8beb6faa037f1b6e2ecb3e252bdac"
|
||||||
"a9ed85bd1ea?size=158&rating=g&default=404"
|
"6cf71fb567ae36025a9d4ea86b?size=158&rating=g&default=404"
|
||||||
),
|
),
|
||||||
text="foo",
|
text="foo",
|
||||||
)
|
)
|
||||||
|
@ -4,7 +4,7 @@ from django.utils.text import slugify
|
|||||||
|
|
||||||
from authentik.brands.models import Brand
|
from authentik.brands.models import Brand
|
||||||
from authentik.core.models import Group, User
|
from authentik.core.models import Group, User
|
||||||
from authentik.crypto.builder import CertificateBuilder
|
from authentik.crypto.builder import CertificateBuilder, PrivateKeyAlg
|
||||||
from authentik.crypto.models import CertificateKeyPair
|
from authentik.crypto.models import CertificateKeyPair
|
||||||
from authentik.flows.models import Flow, FlowDesignation
|
from authentik.flows.models import Flow, FlowDesignation
|
||||||
from authentik.lib.generators import generate_id
|
from authentik.lib.generators import generate_id
|
||||||
@ -50,12 +50,10 @@ def create_test_brand(**kwargs) -> Brand:
|
|||||||
return Brand.objects.create(domain=uid, default=True, **kwargs)
|
return Brand.objects.create(domain=uid, default=True, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
def create_test_cert(use_ec_private_key=False) -> CertificateKeyPair:
|
def create_test_cert(alg=PrivateKeyAlg.RSA) -> CertificateKeyPair:
|
||||||
"""Generate a certificate for testing"""
|
"""Generate a certificate for testing"""
|
||||||
builder = CertificateBuilder(
|
builder = CertificateBuilder(f"{generate_id()}.self-signed.goauthentik.io")
|
||||||
name=f"{generate_id()}.self-signed.goauthentik.io",
|
builder.alg = alg
|
||||||
use_ec_private_key=use_ec_private_key,
|
|
||||||
)
|
|
||||||
builder.build(
|
builder.build(
|
||||||
subject_alt_names=[f"{generate_id()}.self-signed.goauthentik.io"],
|
subject_alt_names=[f"{generate_id()}.self-signed.goauthentik.io"],
|
||||||
validity_days=360,
|
validity_days=360,
|
||||||
|
@ -12,7 +12,7 @@ from authentik.core.api.applications import ApplicationViewSet
|
|||||||
from authentik.core.api.authenticated_sessions import AuthenticatedSessionViewSet
|
from authentik.core.api.authenticated_sessions import AuthenticatedSessionViewSet
|
||||||
from authentik.core.api.devices import AdminDeviceViewSet, DeviceViewSet
|
from authentik.core.api.devices import AdminDeviceViewSet, DeviceViewSet
|
||||||
from authentik.core.api.groups import GroupViewSet
|
from authentik.core.api.groups import GroupViewSet
|
||||||
from authentik.core.api.propertymappings import PropertyMappingViewSet
|
from authentik.core.api.property_mappings import PropertyMappingViewSet
|
||||||
from authentik.core.api.providers import ProviderViewSet
|
from authentik.core.api.providers import ProviderViewSet
|
||||||
from authentik.core.api.sources import SourceViewSet, UserSourceConnectionViewSet
|
from authentik.core.api.sources import SourceViewSet, UserSourceConnectionViewSet
|
||||||
from authentik.core.api.tokens import TokenViewSet
|
from authentik.core.api.tokens import TokenViewSet
|
||||||
@ -20,8 +20,9 @@ from authentik.core.api.transactional_applications import TransactionalApplicati
|
|||||||
from authentik.core.api.users import UserViewSet
|
from authentik.core.api.users import UserViewSet
|
||||||
from authentik.core.views import apps
|
from authentik.core.views import apps
|
||||||
from authentik.core.views.debug import AccessDeniedView
|
from authentik.core.views.debug import AccessDeniedView
|
||||||
from authentik.core.views.interface import FlowInterfaceView, InterfaceView
|
from authentik.core.views.interface import InterfaceView
|
||||||
from authentik.core.views.session import EndSessionView
|
from authentik.core.views.session import EndSessionView
|
||||||
|
from authentik.flows.views.interface import FlowInterfaceView
|
||||||
from authentik.root.asgi_middleware import SessionMiddleware
|
from authentik.root.asgi_middleware import SessionMiddleware
|
||||||
from authentik.root.messages.consumer import MessageConsumer
|
from authentik.root.messages.consumer import MessageConsumer
|
||||||
from authentik.root.middleware import ChannelsLoggingMiddleware
|
from authentik.root.middleware import ChannelsLoggingMiddleware
|
||||||
@ -53,6 +54,8 @@ urlpatterns = [
|
|||||||
),
|
),
|
||||||
path(
|
path(
|
||||||
"if/flow/<slug:flow_slug>/",
|
"if/flow/<slug:flow_slug>/",
|
||||||
|
# FIXME: move this url to the flows app...also will cause all
|
||||||
|
# of the reverse calls to be adjusted
|
||||||
ensure_csrf_cookie(FlowInterfaceView.as_view()),
|
ensure_csrf_cookie(FlowInterfaceView.as_view()),
|
||||||
name="if-flow",
|
name="if-flow",
|
||||||
),
|
),
|
||||||
|
@ -8,7 +8,6 @@ from django.views import View
|
|||||||
from authentik.core.models import Application
|
from authentik.core.models import Application
|
||||||
from authentik.flows.challenge import (
|
from authentik.flows.challenge import (
|
||||||
ChallengeResponse,
|
ChallengeResponse,
|
||||||
ChallengeTypes,
|
|
||||||
HttpChallengeResponse,
|
HttpChallengeResponse,
|
||||||
RedirectChallenge,
|
RedirectChallenge,
|
||||||
)
|
)
|
||||||
@ -74,7 +73,6 @@ class RedirectToAppStage(ChallengeStageView):
|
|||||||
raise Http404
|
raise Http404
|
||||||
return RedirectChallenge(
|
return RedirectChallenge(
|
||||||
instance={
|
instance={
|
||||||
"type": ChallengeTypes.REDIRECT.value,
|
|
||||||
"to": launch,
|
"to": launch,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
@ -3,7 +3,6 @@
|
|||||||
from json import dumps
|
from json import dumps
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from django.shortcuts import get_object_or_404
|
|
||||||
from django.views.generic.base import TemplateView
|
from django.views.generic.base import TemplateView
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
|
|
||||||
@ -11,7 +10,6 @@ from authentik import get_build_hash
|
|||||||
from authentik.admin.tasks import LOCAL_VERSION
|
from authentik.admin.tasks import LOCAL_VERSION
|
||||||
from authentik.api.v3.config import ConfigView
|
from authentik.api.v3.config import ConfigView
|
||||||
from authentik.brands.api import CurrentBrandSerializer
|
from authentik.brands.api import CurrentBrandSerializer
|
||||||
from authentik.flows.models import Flow
|
|
||||||
|
|
||||||
|
|
||||||
class InterfaceView(TemplateView):
|
class InterfaceView(TemplateView):
|
||||||
@ -25,14 +23,3 @@ class InterfaceView(TemplateView):
|
|||||||
kwargs["build"] = get_build_hash()
|
kwargs["build"] = get_build_hash()
|
||||||
kwargs["url_kwargs"] = self.kwargs
|
kwargs["url_kwargs"] = self.kwargs
|
||||||
return super().get_context_data(**kwargs)
|
return super().get_context_data(**kwargs)
|
||||||
|
|
||||||
|
|
||||||
class FlowInterfaceView(InterfaceView):
|
|
||||||
"""Flow interface"""
|
|
||||||
|
|
||||||
template_name = "if/flow.html"
|
|
||||||
|
|
||||||
def get_context_data(self, **kwargs: Any) -> dict[str, Any]:
|
|
||||||
kwargs["flow"] = get_object_or_404(Flow, slug=self.kwargs.get("flow_slug"))
|
|
||||||
kwargs["inspector"] = "inspector" in self.request.GET
|
|
||||||
return super().get_context_data(**kwargs)
|
|
||||||
|
@ -14,19 +14,24 @@ from drf_spectacular.types import OpenApiTypes
|
|||||||
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
|
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
|
||||||
from rest_framework.decorators import action
|
from rest_framework.decorators import action
|
||||||
from rest_framework.exceptions import ValidationError
|
from rest_framework.exceptions import ValidationError
|
||||||
from rest_framework.fields import CharField, DateTimeField, IntegerField, SerializerMethodField
|
from rest_framework.fields import (
|
||||||
|
CharField,
|
||||||
|
ChoiceField,
|
||||||
|
DateTimeField,
|
||||||
|
IntegerField,
|
||||||
|
SerializerMethodField,
|
||||||
|
)
|
||||||
from rest_framework.filters import OrderingFilter, SearchFilter
|
from rest_framework.filters import OrderingFilter, SearchFilter
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.serializers import ModelSerializer
|
|
||||||
from rest_framework.viewsets import ModelViewSet
|
from rest_framework.viewsets import ModelViewSet
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik.api.authorization import SecretKeyFilter
|
from authentik.api.authorization import SecretKeyFilter
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.utils import PassiveSerializer
|
from authentik.core.api.utils import ModelSerializer, PassiveSerializer
|
||||||
from authentik.crypto.apps import MANAGED_KEY
|
from authentik.crypto.apps import MANAGED_KEY
|
||||||
from authentik.crypto.builder import CertificateBuilder
|
from authentik.crypto.builder import CertificateBuilder, PrivateKeyAlg
|
||||||
from authentik.crypto.models import CertificateKeyPair
|
from authentik.crypto.models import CertificateKeyPair
|
||||||
from authentik.events.models import Event, EventAction
|
from authentik.events.models import Event, EventAction
|
||||||
from authentik.rbac.decorators import permission_required
|
from authentik.rbac.decorators import permission_required
|
||||||
@ -71,7 +76,7 @@ class CertificateKeyPairSerializer(ModelSerializer):
|
|||||||
"Get certificate expiry"
|
"Get certificate expiry"
|
||||||
if not self._should_include_details:
|
if not self._should_include_details:
|
||||||
return None
|
return None
|
||||||
return DateTimeField().to_representation(instance.certificate.not_valid_after)
|
return DateTimeField().to_representation(instance.certificate.not_valid_after_utc)
|
||||||
|
|
||||||
def get_cert_subject(self, instance: CertificateKeyPair) -> str | None:
|
def get_cert_subject(self, instance: CertificateKeyPair) -> str | None:
|
||||||
"""Get certificate subject as full rfc4514"""
|
"""Get certificate subject as full rfc4514"""
|
||||||
@ -178,6 +183,7 @@ class CertificateGenerationSerializer(PassiveSerializer):
|
|||||||
common_name = CharField()
|
common_name = CharField()
|
||||||
subject_alt_name = CharField(required=False, allow_blank=True, label=_("Subject-alt name"))
|
subject_alt_name = CharField(required=False, allow_blank=True, label=_("Subject-alt name"))
|
||||||
validity_days = IntegerField(initial=365)
|
validity_days = IntegerField(initial=365)
|
||||||
|
alg = ChoiceField(default=PrivateKeyAlg.RSA, choices=PrivateKeyAlg.choices)
|
||||||
|
|
||||||
|
|
||||||
class CertificateKeyPairFilter(FilterSet):
|
class CertificateKeyPairFilter(FilterSet):
|
||||||
@ -240,6 +246,7 @@ class CertificateKeyPairViewSet(UsedByMixin, ModelViewSet):
|
|||||||
raw_san = data.validated_data.get("subject_alt_name", "")
|
raw_san = data.validated_data.get("subject_alt_name", "")
|
||||||
sans = raw_san.split(",") if raw_san != "" else []
|
sans = raw_san.split(",") if raw_san != "" else []
|
||||||
builder = CertificateBuilder(data.validated_data["common_name"])
|
builder = CertificateBuilder(data.validated_data["common_name"])
|
||||||
|
builder.alg = data.validated_data["alg"]
|
||||||
builder.build(
|
builder.build(
|
||||||
subject_alt_names=sans,
|
subject_alt_names=sans,
|
||||||
validity_days=int(data.validated_data["validity_days"]),
|
validity_days=int(data.validated_data["validity_days"]),
|
||||||
|
@ -9,20 +9,28 @@ from cryptography.hazmat.primitives import hashes, serialization
|
|||||||
from cryptography.hazmat.primitives.asymmetric import ec, rsa
|
from cryptography.hazmat.primitives.asymmetric import ec, rsa
|
||||||
from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes
|
from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes
|
||||||
from cryptography.x509.oid import NameOID
|
from cryptography.x509.oid import NameOID
|
||||||
|
from django.db import models
|
||||||
|
from django.utils.translation import gettext_lazy as _
|
||||||
|
|
||||||
from authentik import __version__
|
from authentik import __version__
|
||||||
from authentik.crypto.models import CertificateKeyPair
|
from authentik.crypto.models import CertificateKeyPair
|
||||||
|
|
||||||
|
|
||||||
|
class PrivateKeyAlg(models.TextChoices):
|
||||||
|
"""Algorithm to create private key with"""
|
||||||
|
|
||||||
|
RSA = "rsa", _("rsa")
|
||||||
|
ECDSA = "ecdsa", _("ecdsa")
|
||||||
|
|
||||||
|
|
||||||
class CertificateBuilder:
|
class CertificateBuilder:
|
||||||
"""Build self-signed certificates"""
|
"""Build self-signed certificates"""
|
||||||
|
|
||||||
common_name: str
|
common_name: str
|
||||||
|
alg: PrivateKeyAlg
|
||||||
|
|
||||||
_use_ec_private_key: bool
|
def __init__(self, name: str):
|
||||||
|
self.alg = PrivateKeyAlg.RSA
|
||||||
def __init__(self, name: str, use_ec_private_key=False):
|
|
||||||
self._use_ec_private_key = use_ec_private_key
|
|
||||||
self.__public_key = None
|
self.__public_key = None
|
||||||
self.__private_key = None
|
self.__private_key = None
|
||||||
self.__builder = None
|
self.__builder = None
|
||||||
@ -42,11 +50,13 @@ class CertificateBuilder:
|
|||||||
|
|
||||||
def generate_private_key(self) -> PrivateKeyTypes:
|
def generate_private_key(self) -> PrivateKeyTypes:
|
||||||
"""Generate private key"""
|
"""Generate private key"""
|
||||||
if self._use_ec_private_key:
|
if self.alg == PrivateKeyAlg.ECDSA:
|
||||||
return ec.generate_private_key(curve=ec.SECP256R1())
|
return ec.generate_private_key(curve=ec.SECP256R1())
|
||||||
return rsa.generate_private_key(
|
if self.alg == PrivateKeyAlg.RSA:
|
||||||
public_exponent=65537, key_size=4096, backend=default_backend()
|
return rsa.generate_private_key(
|
||||||
)
|
public_exponent=65537, key_size=4096, backend=default_backend()
|
||||||
|
)
|
||||||
|
raise ValueError(f"Invalid alg: {self.alg}")
|
||||||
|
|
||||||
def build(
|
def build(
|
||||||
self,
|
self,
|
||||||
|
@ -92,7 +92,11 @@ class CertificateKeyPair(SerializerModel, ManagedModel, CreatedUpdatedModel):
|
|||||||
@property
|
@property
|
||||||
def kid(self):
|
def kid(self):
|
||||||
"""Get Key ID used for JWKS"""
|
"""Get Key ID used for JWKS"""
|
||||||
return md5(self.key_data.encode("utf-8")).hexdigest() if self.key_data else "" # nosec
|
return (
|
||||||
|
md5(self.key_data.encode("utf-8"), usedforsecurity=False).hexdigest()
|
||||||
|
if self.key_data
|
||||||
|
else ""
|
||||||
|
) # nosec
|
||||||
|
|
||||||
def __str__(self) -> str:
|
def __str__(self) -> str:
|
||||||
return f"Certificate-Key Pair {self.name}"
|
return f"Certificate-Key Pair {self.name}"
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
"""Crypto tests"""
|
"""Crypto tests"""
|
||||||
|
|
||||||
import datetime
|
|
||||||
from json import loads
|
from json import loads
|
||||||
from os import makedirs
|
from os import makedirs
|
||||||
from tempfile import TemporaryDirectory
|
from tempfile import TemporaryDirectory
|
||||||
@ -8,6 +7,7 @@ from tempfile import TemporaryDirectory
|
|||||||
from cryptography.x509.extensions import SubjectAlternativeName
|
from cryptography.x509.extensions import SubjectAlternativeName
|
||||||
from cryptography.x509.general_name import DNSName
|
from cryptography.x509.general_name import DNSName
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
|
from django.utils.timezone import now
|
||||||
from rest_framework.test import APITestCase
|
from rest_framework.test import APITestCase
|
||||||
|
|
||||||
from authentik.core.api.used_by import DeleteAction
|
from authentik.core.api.used_by import DeleteAction
|
||||||
@ -68,9 +68,9 @@ class TestCrypto(APITestCase):
|
|||||||
validity_days=3,
|
validity_days=3,
|
||||||
)
|
)
|
||||||
instance = builder.save()
|
instance = builder.save()
|
||||||
now = datetime.datetime.today()
|
_now = now()
|
||||||
self.assertEqual(instance.name, name)
|
self.assertEqual(instance.name, name)
|
||||||
self.assertEqual((instance.certificate.not_valid_after - now).days, 2)
|
self.assertEqual((instance.certificate.not_valid_after_utc - _now).days, 2)
|
||||||
|
|
||||||
def test_builder_api(self):
|
def test_builder_api(self):
|
||||||
"""Test Builder (via API)"""
|
"""Test Builder (via API)"""
|
||||||
@ -241,7 +241,7 @@ class TestCrypto(APITestCase):
|
|||||||
"model_name": "oauth2provider",
|
"model_name": "oauth2provider",
|
||||||
"pk": str(provider.pk),
|
"pk": str(provider.pk),
|
||||||
"name": str(provider),
|
"name": str(provider),
|
||||||
"action": DeleteAction.SET_NULL.name,
|
"action": DeleteAction.SET_NULL.value,
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
|
@ -13,16 +13,15 @@ from rest_framework.fields import CharField, IntegerField
|
|||||||
from rest_framework.permissions import IsAuthenticated
|
from rest_framework.permissions import IsAuthenticated
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.serializers import ModelSerializer
|
|
||||||
from rest_framework.viewsets import ModelViewSet
|
from rest_framework.viewsets import ModelViewSet
|
||||||
|
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.utils import PassiveSerializer
|
from authentik.core.api.utils import ModelSerializer, PassiveSerializer
|
||||||
from authentik.core.models import User, UserTypes
|
from authentik.core.models import User, UserTypes
|
||||||
from authentik.enterprise.license import LicenseKey, LicenseSummarySerializer
|
from authentik.enterprise.license import LicenseKey, LicenseSummarySerializer
|
||||||
from authentik.enterprise.models import License
|
from authentik.enterprise.models import License
|
||||||
from authentik.rbac.decorators import permission_required
|
from authentik.rbac.decorators import permission_required
|
||||||
from authentik.root.install_id import get_install_id
|
from authentik.tenants.utils import get_unique_identifier
|
||||||
|
|
||||||
|
|
||||||
class EnterpriseRequiredMixin:
|
class EnterpriseRequiredMixin:
|
||||||
@ -31,7 +30,7 @@ class EnterpriseRequiredMixin:
|
|||||||
|
|
||||||
def validate(self, attrs: dict) -> dict:
|
def validate(self, attrs: dict) -> dict:
|
||||||
"""Check that a valid license exists"""
|
"""Check that a valid license exists"""
|
||||||
if not LicenseKey.cached_summary().valid:
|
if not LicenseKey.cached_summary().has_license:
|
||||||
raise ValidationError(_("Enterprise is required to create/update this object."))
|
raise ValidationError(_("Enterprise is required to create/update this object."))
|
||||||
return super().validate(attrs)
|
return super().validate(attrs)
|
||||||
|
|
||||||
@ -92,7 +91,7 @@ class LicenseViewSet(UsedByMixin, ModelViewSet):
|
|||||||
"""Get install_id"""
|
"""Get install_id"""
|
||||||
return Response(
|
return Response(
|
||||||
data={
|
data={
|
||||||
"install_id": get_install_id(),
|
"install_id": get_unique_identifier(),
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -13,9 +13,9 @@ class AuthentikEnterpriseAuditConfig(EnterpriseConfig):
|
|||||||
verbose_name = "authentik Enterprise.Audit"
|
verbose_name = "authentik Enterprise.Audit"
|
||||||
default = True
|
default = True
|
||||||
|
|
||||||
@EnterpriseConfig.reconcile_global
|
def ready(self):
|
||||||
def install_middleware(self):
|
|
||||||
"""Install enterprise audit middleware"""
|
"""Install enterprise audit middleware"""
|
||||||
orig_import = "authentik.events.middleware.AuditMiddleware"
|
orig_import = "authentik.events.middleware.AuditMiddleware"
|
||||||
new_import = "authentik.enterprise.audit.middleware.EnterpriseAuditMiddleware"
|
new_import = "authentik.enterprise.audit.middleware.EnterpriseAuditMiddleware"
|
||||||
settings.MIDDLEWARE = [new_import if x == orig_import else x for x in settings.MIDDLEWARE]
|
settings.MIDDLEWARE = [new_import if x == orig_import else x for x in settings.MIDDLEWARE]
|
||||||
|
return super().ready()
|
||||||
|
@ -2,16 +2,16 @@
|
|||||||
|
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
from functools import partial
|
from functools import partial
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
from django.apps.registry import apps
|
from django.apps.registry import apps
|
||||||
from django.core.files import File
|
from django.core.files import File
|
||||||
from django.db import connection
|
from django.db import connection
|
||||||
from django.db.models import Model
|
from django.db.models import ManyToManyRel, Model
|
||||||
from django.db.models.expressions import BaseExpression, Combinable
|
from django.db.models.expressions import BaseExpression, Combinable
|
||||||
from django.db.models.signals import post_init
|
from django.db.models.signals import post_init
|
||||||
from django.http import HttpRequest
|
from django.http import HttpRequest
|
||||||
|
|
||||||
from authentik.core.models import User
|
|
||||||
from authentik.events.middleware import AuditMiddleware, should_log_model
|
from authentik.events.middleware import AuditMiddleware, should_log_model
|
||||||
from authentik.events.utils import cleanse_dict, sanitize_item
|
from authentik.events.utils import cleanse_dict, sanitize_item
|
||||||
|
|
||||||
@ -28,13 +28,10 @@ class EnterpriseAuditMiddleware(AuditMiddleware):
|
|||||||
super().connect(request)
|
super().connect(request)
|
||||||
if not self.enabled:
|
if not self.enabled:
|
||||||
return
|
return
|
||||||
user = getattr(request, "user", self.anonymous_user)
|
|
||||||
if not user.is_authenticated:
|
|
||||||
user = self.anonymous_user
|
|
||||||
if not hasattr(request, "request_id"):
|
if not hasattr(request, "request_id"):
|
||||||
return
|
return
|
||||||
post_init.connect(
|
post_init.connect(
|
||||||
partial(self.post_init_handler, user=user, request=request),
|
partial(self.post_init_handler, request=request),
|
||||||
dispatch_uid=request.request_id,
|
dispatch_uid=request.request_id,
|
||||||
weak=False,
|
weak=False,
|
||||||
)
|
)
|
||||||
@ -48,7 +45,7 @@ class EnterpriseAuditMiddleware(AuditMiddleware):
|
|||||||
post_init.disconnect(dispatch_uid=request.request_id)
|
post_init.disconnect(dispatch_uid=request.request_id)
|
||||||
|
|
||||||
def serialize_simple(self, model: Model) -> dict:
|
def serialize_simple(self, model: Model) -> dict:
|
||||||
"""Serialize a model in a very simple way. No ForeginKeys or other relationships are
|
"""Serialize a model in a very simple way. No ForeignKeys or other relationships are
|
||||||
resolved"""
|
resolved"""
|
||||||
data = {}
|
data = {}
|
||||||
deferred_fields = model.get_deferred_fields()
|
deferred_fields = model.get_deferred_fields()
|
||||||
@ -74,9 +71,12 @@ class EnterpriseAuditMiddleware(AuditMiddleware):
|
|||||||
for key, value in before.items():
|
for key, value in before.items():
|
||||||
if after.get(key) != value:
|
if after.get(key) != value:
|
||||||
diff[key] = {"previous_value": value, "new_value": after.get(key)}
|
diff[key] = {"previous_value": value, "new_value": after.get(key)}
|
||||||
|
for key, value in after.items():
|
||||||
|
if key not in before and key not in diff and before.get(key) != value:
|
||||||
|
diff[key] = {"previous_value": before.get(key), "new_value": value}
|
||||||
return sanitize_item(diff)
|
return sanitize_item(diff)
|
||||||
|
|
||||||
def post_init_handler(self, user: User, request: HttpRequest, sender, instance: Model, **_):
|
def post_init_handler(self, request: HttpRequest, sender, instance: Model, **_):
|
||||||
"""post_init django model handler"""
|
"""post_init django model handler"""
|
||||||
if not should_log_model(instance):
|
if not should_log_model(instance):
|
||||||
return
|
return
|
||||||
@ -90,7 +90,6 @@ class EnterpriseAuditMiddleware(AuditMiddleware):
|
|||||||
|
|
||||||
def post_save_handler(
|
def post_save_handler(
|
||||||
self,
|
self,
|
||||||
user: User,
|
|
||||||
request: HttpRequest,
|
request: HttpRequest,
|
||||||
sender,
|
sender,
|
||||||
instance: Model,
|
instance: Model,
|
||||||
@ -103,15 +102,37 @@ class EnterpriseAuditMiddleware(AuditMiddleware):
|
|||||||
thread_kwargs = {}
|
thread_kwargs = {}
|
||||||
if hasattr(instance, "_previous_state") or created:
|
if hasattr(instance, "_previous_state") or created:
|
||||||
prev_state = getattr(instance, "_previous_state", {})
|
prev_state = getattr(instance, "_previous_state", {})
|
||||||
|
if created:
|
||||||
|
prev_state = {}
|
||||||
# Get current state
|
# Get current state
|
||||||
new_state = self.serialize_simple(instance)
|
new_state = self.serialize_simple(instance)
|
||||||
diff = self.diff(prev_state, new_state)
|
diff = self.diff(prev_state, new_state)
|
||||||
thread_kwargs["diff"] = diff
|
thread_kwargs["diff"] = diff
|
||||||
if not created:
|
return super().post_save_handler(request, sender, instance, created, thread_kwargs, **_)
|
||||||
ignored_field_sets = getattr(instance._meta, "authentik_signals_ignored_fields", [])
|
|
||||||
for field_set in ignored_field_sets:
|
def m2m_changed_handler( # noqa: PLR0913
|
||||||
if set(diff.keys()) == set(field_set):
|
self,
|
||||||
return None
|
request: HttpRequest,
|
||||||
return super().post_save_handler(
|
sender,
|
||||||
user, request, sender, instance, created, thread_kwargs, **_
|
instance: Model,
|
||||||
)
|
action: str,
|
||||||
|
pk_set: set[Any],
|
||||||
|
thread_kwargs: dict | None = None,
|
||||||
|
**_,
|
||||||
|
):
|
||||||
|
thread_kwargs = {}
|
||||||
|
m2m_field = None
|
||||||
|
# For the audit log we don't care about `pre_` or `post_` so we trim that part off
|
||||||
|
_, _, action_direction = action.partition("_")
|
||||||
|
# resolve the "through" model to an actual field
|
||||||
|
for field in instance._meta.get_fields():
|
||||||
|
if not isinstance(field, ManyToManyRel):
|
||||||
|
continue
|
||||||
|
if field.through == sender:
|
||||||
|
m2m_field = field
|
||||||
|
if m2m_field:
|
||||||
|
# If we're clearing we just set the "flag" to True
|
||||||
|
if action_direction == "clear":
|
||||||
|
pk_set = True
|
||||||
|
thread_kwargs["diff"] = {m2m_field.related_name: {action_direction: pk_set}}
|
||||||
|
return super().m2m_changed_handler(request, sender, instance, action, thread_kwargs)
|
||||||
|
210
authentik/enterprise/audit/tests.py
Normal file
210
authentik/enterprise/audit/tests.py
Normal file
@ -0,0 +1,210 @@
|
|||||||
|
from unittest.mock import PropertyMock, patch
|
||||||
|
|
||||||
|
from django.apps import apps
|
||||||
|
from django.conf import settings
|
||||||
|
from django.urls import reverse
|
||||||
|
from rest_framework.test import APITestCase
|
||||||
|
|
||||||
|
from authentik.core.models import Group, User
|
||||||
|
from authentik.core.tests.utils import create_test_admin_user
|
||||||
|
from authentik.events.models import Event, EventAction
|
||||||
|
from authentik.events.utils import sanitize_item
|
||||||
|
from authentik.lib.generators import generate_id
|
||||||
|
|
||||||
|
|
||||||
|
class TestEnterpriseAudit(APITestCase):
|
||||||
|
"""Test audit middleware"""
|
||||||
|
|
||||||
|
def setUp(self) -> None:
|
||||||
|
self.user = create_test_admin_user()
|
||||||
|
|
||||||
|
def test_import(self):
|
||||||
|
"""Ensure middleware is imported when app.ready is called"""
|
||||||
|
# Revert import swap
|
||||||
|
orig_import = "authentik.events.middleware.AuditMiddleware"
|
||||||
|
new_import = "authentik.enterprise.audit.middleware.EnterpriseAuditMiddleware"
|
||||||
|
settings.MIDDLEWARE = [orig_import if x == new_import else x for x in settings.MIDDLEWARE]
|
||||||
|
# Re-call ready()
|
||||||
|
apps.get_app_config("authentik_enterprise_audit").ready()
|
||||||
|
self.assertIn(
|
||||||
|
"authentik.enterprise.audit.middleware.EnterpriseAuditMiddleware", settings.MIDDLEWARE
|
||||||
|
)
|
||||||
|
|
||||||
|
@patch(
|
||||||
|
"authentik.enterprise.audit.middleware.EnterpriseAuditMiddleware.enabled",
|
||||||
|
PropertyMock(return_value=True),
|
||||||
|
)
|
||||||
|
def test_create(self):
|
||||||
|
"""Test create audit log"""
|
||||||
|
self.client.force_login(self.user)
|
||||||
|
username = generate_id()
|
||||||
|
response = self.client.post(
|
||||||
|
reverse("authentik_api:user-list"),
|
||||||
|
data={"name": generate_id(), "username": username, "groups": [], "path": "foo"},
|
||||||
|
)
|
||||||
|
user = User.objects.get(username=username)
|
||||||
|
self.assertEqual(response.status_code, 201)
|
||||||
|
events = Event.objects.filter(
|
||||||
|
action=EventAction.MODEL_CREATED,
|
||||||
|
context__model__model_name="user",
|
||||||
|
context__model__app="authentik_core",
|
||||||
|
context__model__pk=user.pk,
|
||||||
|
)
|
||||||
|
event = events.first()
|
||||||
|
self.assertIsNotNone(event)
|
||||||
|
self.assertIsNotNone(event.context["diff"])
|
||||||
|
diff = event.context["diff"]
|
||||||
|
self.assertEqual(
|
||||||
|
diff,
|
||||||
|
{
|
||||||
|
"name": {
|
||||||
|
"new_value": user.name,
|
||||||
|
"previous_value": None,
|
||||||
|
},
|
||||||
|
"path": {"new_value": "foo", "previous_value": None},
|
||||||
|
"type": {"new_value": "internal", "previous_value": None},
|
||||||
|
"uuid": {
|
||||||
|
"new_value": user.uuid.hex,
|
||||||
|
"previous_value": None,
|
||||||
|
},
|
||||||
|
"email": {"new_value": "", "previous_value": None},
|
||||||
|
"username": {
|
||||||
|
"new_value": user.username,
|
||||||
|
"previous_value": None,
|
||||||
|
},
|
||||||
|
"is_active": {"new_value": True, "previous_value": None},
|
||||||
|
"attributes": {"new_value": {}, "previous_value": None},
|
||||||
|
"date_joined": {
|
||||||
|
"new_value": sanitize_item(user.date_joined),
|
||||||
|
"previous_value": None,
|
||||||
|
},
|
||||||
|
"first_name": {"new_value": "", "previous_value": None},
|
||||||
|
"id": {"new_value": user.pk, "previous_value": None},
|
||||||
|
"last_name": {"new_value": "", "previous_value": None},
|
||||||
|
"password": {"new_value": "********************", "previous_value": None},
|
||||||
|
"password_change_date": {
|
||||||
|
"new_value": sanitize_item(user.password_change_date),
|
||||||
|
"previous_value": None,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
@patch(
|
||||||
|
"authentik.enterprise.audit.middleware.EnterpriseAuditMiddleware.enabled",
|
||||||
|
PropertyMock(return_value=True),
|
||||||
|
)
|
||||||
|
def test_update(self):
|
||||||
|
"""Test update audit log"""
|
||||||
|
self.client.force_login(self.user)
|
||||||
|
user = create_test_admin_user()
|
||||||
|
current_name = user.name
|
||||||
|
new_name = generate_id()
|
||||||
|
response = self.client.patch(
|
||||||
|
reverse("authentik_api:user-detail", kwargs={"pk": user.id}),
|
||||||
|
data={"name": new_name},
|
||||||
|
)
|
||||||
|
user.refresh_from_db()
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
events = Event.objects.filter(
|
||||||
|
action=EventAction.MODEL_UPDATED,
|
||||||
|
context__model__model_name="user",
|
||||||
|
context__model__app="authentik_core",
|
||||||
|
context__model__pk=user.pk,
|
||||||
|
)
|
||||||
|
event = events.first()
|
||||||
|
self.assertIsNotNone(event)
|
||||||
|
self.assertIsNotNone(event.context["diff"])
|
||||||
|
diff = event.context["diff"]
|
||||||
|
self.assertEqual(
|
||||||
|
diff,
|
||||||
|
{
|
||||||
|
"name": {
|
||||||
|
"new_value": new_name,
|
||||||
|
"previous_value": current_name,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
@patch(
|
||||||
|
"authentik.enterprise.audit.middleware.EnterpriseAuditMiddleware.enabled",
|
||||||
|
PropertyMock(return_value=True),
|
||||||
|
)
|
||||||
|
def test_delete(self):
|
||||||
|
"""Test delete audit log"""
|
||||||
|
self.client.force_login(self.user)
|
||||||
|
user = create_test_admin_user()
|
||||||
|
response = self.client.delete(
|
||||||
|
reverse("authentik_api:user-detail", kwargs={"pk": user.id}),
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 204)
|
||||||
|
events = Event.objects.filter(
|
||||||
|
action=EventAction.MODEL_DELETED,
|
||||||
|
context__model__model_name="user",
|
||||||
|
context__model__app="authentik_core",
|
||||||
|
context__model__pk=user.pk,
|
||||||
|
)
|
||||||
|
event = events.first()
|
||||||
|
self.assertIsNotNone(event)
|
||||||
|
self.assertNotIn("diff", event.context)
|
||||||
|
|
||||||
|
@patch(
|
||||||
|
"authentik.enterprise.audit.middleware.EnterpriseAuditMiddleware.enabled",
|
||||||
|
PropertyMock(return_value=True),
|
||||||
|
)
|
||||||
|
def test_m2m_add(self):
|
||||||
|
"""Test m2m add audit log"""
|
||||||
|
self.client.force_login(self.user)
|
||||||
|
user = create_test_admin_user()
|
||||||
|
group = Group.objects.create(name=generate_id())
|
||||||
|
response = self.client.post(
|
||||||
|
reverse("authentik_api:group-add-user", kwargs={"pk": group.group_uuid}),
|
||||||
|
data={
|
||||||
|
"pk": user.pk,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 204)
|
||||||
|
events = Event.objects.filter(
|
||||||
|
action=EventAction.MODEL_UPDATED,
|
||||||
|
context__model__model_name="group",
|
||||||
|
context__model__app="authentik_core",
|
||||||
|
context__model__pk=group.pk.hex,
|
||||||
|
)
|
||||||
|
event = events.first()
|
||||||
|
self.assertIsNotNone(event)
|
||||||
|
self.assertIsNotNone(event.context["diff"])
|
||||||
|
diff = event.context["diff"]
|
||||||
|
self.assertEqual(
|
||||||
|
diff,
|
||||||
|
{"users": {"add": [user.pk]}},
|
||||||
|
)
|
||||||
|
|
||||||
|
@patch(
|
||||||
|
"authentik.enterprise.audit.middleware.EnterpriseAuditMiddleware.enabled",
|
||||||
|
PropertyMock(return_value=True),
|
||||||
|
)
|
||||||
|
def test_m2m_remove(self):
|
||||||
|
"""Test m2m remove audit log"""
|
||||||
|
self.client.force_login(self.user)
|
||||||
|
user = create_test_admin_user()
|
||||||
|
group = Group.objects.create(name=generate_id())
|
||||||
|
response = self.client.post(
|
||||||
|
reverse("authentik_api:group-remove-user", kwargs={"pk": group.group_uuid}),
|
||||||
|
data={
|
||||||
|
"pk": user.pk,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 204)
|
||||||
|
events = Event.objects.filter(
|
||||||
|
action=EventAction.MODEL_UPDATED,
|
||||||
|
context__model__model_name="group",
|
||||||
|
context__model__app="authentik_core",
|
||||||
|
context__model__pk=group.pk.hex,
|
||||||
|
)
|
||||||
|
event = events.first()
|
||||||
|
self.assertIsNotNone(event)
|
||||||
|
self.assertIsNotNone(event.context["diff"])
|
||||||
|
diff = event.context["diff"]
|
||||||
|
self.assertEqual(
|
||||||
|
diff,
|
||||||
|
{"users": {"remove": [user.pk]}},
|
||||||
|
)
|
@ -21,7 +21,7 @@ from rest_framework.fields import BooleanField, DateTimeField, IntegerField
|
|||||||
from authentik.core.api.utils import PassiveSerializer
|
from authentik.core.api.utils import PassiveSerializer
|
||||||
from authentik.core.models import User, UserTypes
|
from authentik.core.models import User, UserTypes
|
||||||
from authentik.enterprise.models import License, LicenseUsage
|
from authentik.enterprise.models import License, LicenseUsage
|
||||||
from authentik.root.install_id import get_install_id
|
from authentik.tenants.utils import get_unique_identifier
|
||||||
|
|
||||||
CACHE_KEY_ENTERPRISE_LICENSE = "goauthentik.io/enterprise/license"
|
CACHE_KEY_ENTERPRISE_LICENSE = "goauthentik.io/enterprise/license"
|
||||||
CACHE_EXPIRY_ENTERPRISE_LICENSE = 3 * 60 * 60 # 2 Hours
|
CACHE_EXPIRY_ENTERPRISE_LICENSE = 3 * 60 * 60 # 2 Hours
|
||||||
@ -36,7 +36,7 @@ def get_licensing_key() -> Certificate:
|
|||||||
|
|
||||||
def get_license_aud() -> str:
|
def get_license_aud() -> str:
|
||||||
"""Get the JWT audience field"""
|
"""Get the JWT audience field"""
|
||||||
return f"enterprise.goauthentik.io/license/{get_install_id()}"
|
return f"enterprise.goauthentik.io/license/{get_unique_identifier()}"
|
||||||
|
|
||||||
|
|
||||||
class LicenseFlags(Enum):
|
class LicenseFlags(Enum):
|
||||||
@ -142,13 +142,7 @@ class LicenseKey:
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def get_external_user_count():
|
def get_external_user_count():
|
||||||
"""Get current external user count"""
|
"""Get current external user count"""
|
||||||
# Count since start of the month
|
return LicenseKey.base_user_qs().filter(type=UserTypes.EXTERNAL).count()
|
||||||
last_month = now().replace(day=1)
|
|
||||||
return (
|
|
||||||
LicenseKey.base_user_qs()
|
|
||||||
.filter(type=UserTypes.EXTERNAL, last_login__gte=last_month)
|
|
||||||
.count()
|
|
||||||
)
|
|
||||||
|
|
||||||
def is_valid(self) -> bool:
|
def is_valid(self) -> bool:
|
||||||
"""Check if the given license body covers all users
|
"""Check if the given license body covers all users
|
||||||
@ -188,20 +182,21 @@ class LicenseKey:
|
|||||||
|
|
||||||
def summary(self) -> LicenseSummary:
|
def summary(self) -> LicenseSummary:
|
||||||
"""Summary of license status"""
|
"""Summary of license status"""
|
||||||
|
has_license = License.objects.all().count() > 0
|
||||||
last_valid = LicenseKey.last_valid_date()
|
last_valid = LicenseKey.last_valid_date()
|
||||||
show_admin_warning = last_valid < now() - timedelta(weeks=2)
|
show_admin_warning = last_valid < now() - timedelta(weeks=2)
|
||||||
show_user_warning = last_valid < now() - timedelta(weeks=4)
|
show_user_warning = last_valid < now() - timedelta(weeks=4)
|
||||||
read_only = last_valid < now() - timedelta(weeks=6)
|
read_only = last_valid < now() - timedelta(weeks=6)
|
||||||
latest_valid = datetime.fromtimestamp(self.exp)
|
latest_valid = datetime.fromtimestamp(self.exp)
|
||||||
return LicenseSummary(
|
return LicenseSummary(
|
||||||
show_admin_warning=show_admin_warning,
|
show_admin_warning=show_admin_warning and has_license,
|
||||||
show_user_warning=show_user_warning,
|
show_user_warning=show_user_warning and has_license,
|
||||||
read_only=read_only,
|
read_only=read_only and has_license,
|
||||||
latest_valid=latest_valid,
|
latest_valid=latest_valid,
|
||||||
internal_users=self.internal_users,
|
internal_users=self.internal_users,
|
||||||
external_users=self.external_users,
|
external_users=self.external_users,
|
||||||
valid=self.is_valid(),
|
valid=self.is_valid(),
|
||||||
has_license=License.objects.all().count() > 0,
|
has_license=has_license,
|
||||||
)
|
)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
@ -0,0 +1,47 @@
|
|||||||
|
"""GoogleWorkspaceProviderGroup API Views"""
|
||||||
|
|
||||||
|
from rest_framework import mixins
|
||||||
|
from rest_framework.viewsets import GenericViewSet
|
||||||
|
|
||||||
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
|
from authentik.core.api.users import UserGroupSerializer
|
||||||
|
from authentik.core.api.utils import ModelSerializer
|
||||||
|
from authentik.enterprise.providers.google_workspace.models import GoogleWorkspaceProviderGroup
|
||||||
|
from authentik.lib.sync.outgoing.api import OutgoingSyncConnectionCreateMixin
|
||||||
|
|
||||||
|
|
||||||
|
class GoogleWorkspaceProviderGroupSerializer(ModelSerializer):
|
||||||
|
"""GoogleWorkspaceProviderGroup Serializer"""
|
||||||
|
|
||||||
|
group_obj = UserGroupSerializer(source="group", read_only=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
|
||||||
|
model = GoogleWorkspaceProviderGroup
|
||||||
|
fields = [
|
||||||
|
"id",
|
||||||
|
"google_id",
|
||||||
|
"group",
|
||||||
|
"group_obj",
|
||||||
|
"provider",
|
||||||
|
"attributes",
|
||||||
|
]
|
||||||
|
extra_kwargs = {"attributes": {"read_only": True}}
|
||||||
|
|
||||||
|
|
||||||
|
class GoogleWorkspaceProviderGroupViewSet(
|
||||||
|
mixins.CreateModelMixin,
|
||||||
|
OutgoingSyncConnectionCreateMixin,
|
||||||
|
mixins.RetrieveModelMixin,
|
||||||
|
mixins.DestroyModelMixin,
|
||||||
|
UsedByMixin,
|
||||||
|
mixins.ListModelMixin,
|
||||||
|
GenericViewSet,
|
||||||
|
):
|
||||||
|
"""GoogleWorkspaceProviderGroup Viewset"""
|
||||||
|
|
||||||
|
queryset = GoogleWorkspaceProviderGroup.objects.all().select_related("group")
|
||||||
|
serializer_class = GoogleWorkspaceProviderGroupSerializer
|
||||||
|
filterset_fields = ["provider__id", "group__name", "group__group_uuid"]
|
||||||
|
search_fields = ["provider__name", "group__name"]
|
||||||
|
ordering = ["group__name"]
|
@ -0,0 +1,39 @@
|
|||||||
|
"""google Property mappings API Views"""
|
||||||
|
|
||||||
|
from django_filters.filters import AllValuesMultipleFilter
|
||||||
|
from django_filters.filterset import FilterSet
|
||||||
|
from drf_spectacular.types import OpenApiTypes
|
||||||
|
from drf_spectacular.utils import extend_schema_field
|
||||||
|
from rest_framework.viewsets import ModelViewSet
|
||||||
|
|
||||||
|
from authentik.core.api.property_mappings import PropertyMappingSerializer
|
||||||
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
|
from authentik.enterprise.providers.google_workspace.models import GoogleWorkspaceProviderMapping
|
||||||
|
|
||||||
|
|
||||||
|
class GoogleWorkspaceProviderMappingSerializer(PropertyMappingSerializer):
|
||||||
|
"""GoogleWorkspaceProviderMapping Serializer"""
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = GoogleWorkspaceProviderMapping
|
||||||
|
fields = PropertyMappingSerializer.Meta.fields
|
||||||
|
|
||||||
|
|
||||||
|
class GoogleWorkspaceProviderMappingFilter(FilterSet):
|
||||||
|
"""Filter for GoogleWorkspaceProviderMapping"""
|
||||||
|
|
||||||
|
managed = extend_schema_field(OpenApiTypes.STR)(AllValuesMultipleFilter(field_name="managed"))
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = GoogleWorkspaceProviderMapping
|
||||||
|
fields = "__all__"
|
||||||
|
|
||||||
|
|
||||||
|
class GoogleWorkspaceProviderMappingViewSet(UsedByMixin, ModelViewSet):
|
||||||
|
"""GoogleWorkspaceProviderMapping Viewset"""
|
||||||
|
|
||||||
|
queryset = GoogleWorkspaceProviderMapping.objects.all()
|
||||||
|
serializer_class = GoogleWorkspaceProviderMappingSerializer
|
||||||
|
filterset_class = GoogleWorkspaceProviderMappingFilter
|
||||||
|
search_fields = ["name"]
|
||||||
|
ordering = ["name"]
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user