Compare commits
1122 Commits
version/20
...
version-20
Author | SHA1 | Date | |
---|---|---|---|
fd7a7a6e64 | |||
15c34c6f1f | |||
0ab8f4eed7 | |||
070714abe4 | |||
810c04bacf | |||
b624bf1cb7 | |||
f56a4b00ce | |||
6ec0411930 | |||
fb59969bce | |||
eec9c46533 | |||
a3afd47850 | |||
8ffae4505f | |||
0cc83c23c4 | |||
514c48a986 | |||
fdb8fb4b4c | |||
d8a68407f9 | |||
417156d659 | |||
9d58407e25 | |||
f4441c9fcf | |||
0e9762072a | |||
0cfffa28ad | |||
1ad4c8fc29 | |||
dd2facdc57 | |||
549dfa4c3a | |||
7f8ae24e8d | |||
d05aeb91f2 | |||
ab25216c1f | |||
fb5eb7b868 | |||
bda218f7fc | |||
198c940a80 | |||
c900411d5a | |||
1adc6948b4 | |||
e87236b285 | |||
846b63a17b | |||
48fb3c98ff | |||
b488a6fec9 | |||
f014bd5f30 | |||
03dd079e8c | |||
1281e842d1 | |||
f7601d9571 | |||
4d9c9160e7 | |||
ad1f913e54 | |||
3da0233c40 | |||
ff788edd9b | |||
aea0958f3f | |||
1f9e9f9ca0 | |||
98ffec87c0 | |||
b52d5dccac | |||
e96a4fa181 | |||
c53b0830c4 | |||
435d126a1c | |||
ef5407be33 | |||
e8b30b75d2 | |||
2c09ac4fd6 | |||
e9c1276634 | |||
71d6304407 | |||
6000a33a8e | |||
54eeb7add6 | |||
d7e8ca1c8f | |||
740f4c7d56 | |||
088eb716fc | |||
fb08e1db2b | |||
f1b167c134 | |||
36d0817579 | |||
d4c1ef36f9 | |||
102b191e94 | |||
c735267373 | |||
55b5e9834d | |||
4386ffb8d7 | |||
ca2b1a9c3e | |||
22d33bb796 | |||
ab15846480 | |||
61f4049e51 | |||
5ac4542f37 | |||
0bba536187 | |||
e48d5a5fda | |||
4c9878313c | |||
6356ddd9f3 | |||
7ea0b4b9e4 | |||
a520a60c82 | |||
54c16129ea | |||
2858682866 | |||
b1f7dfaeb4 | |||
eb27be222f | |||
bcbeaa8382 | |||
d5cb95fedd | |||
fda0da4659 | |||
1c569c79f3 | |||
872c18dddc | |||
201bea6d30 | |||
7e3c21d77b | |||
d1a02cbc0c | |||
da666871dd | |||
2fa6cf855d | |||
3b86144ae5 | |||
f01f10c5e5 | |||
e1249d3760 | |||
dcbf106daa | |||
0227ba90bb | |||
b095d63b4d | |||
20648808bc | |||
89fef0ae72 | |||
85640d402f | |||
d5703dce39 | |||
ec42d378ab | |||
2a5a975d9a | |||
a398e2470b | |||
2ce8e18bab | |||
9a9c826c0b | |||
612587dd34 | |||
506722587d | |||
c158604424 | |||
4af6f29025 | |||
d1004e3798 | |||
20aeed139d | |||
b2dbc87a4f | |||
11bd7c72e0 | |||
896cf7594e | |||
457eeb10ab | |||
0d94ffb91b | |||
bd4fccb97b | |||
0cfae088f5 | |||
b4e7663209 | |||
bdca49b265 | |||
c22954b6a4 | |||
dfe97625f0 | |||
74bc0a6301 | |||
2bd29e2fdd | |||
3cd0a782af | |||
d88ce7a43f | |||
a023eee9bf | |||
7a05c6faef | |||
6ab85f7f18 | |||
d12907b81f | |||
553989d17f | |||
475019202b | |||
a9bca55b95 | |||
89c84f10d0 | |||
882250a85e | |||
db1dd196e0 | |||
d4b8dd7fcc | |||
fcf4657833 | |||
393d7ec486 | |||
b7b5168910 | |||
1dcec17a58 | |||
b41acebf5b | |||
e0478e1775 | |||
d6b1a22563 | |||
cada292e00 | |||
d4af47f576 | |||
83eba36f8d | |||
b82a142745 | |||
2a42c203b2 | |||
ade2d4879c | |||
e14798dcdc | |||
e49050af19 | |||
0248755cda | |||
1f90359310 | |||
008fc19f0d | |||
5cd5b71b18 | |||
253d98ba73 | |||
3e2c04d029 | |||
32d3e33c83 | |||
282ebeb38b | |||
81f4d86e6d | |||
bcb90997bb | |||
277df4f04f | |||
de26c65fa0 | |||
55739ee982 | |||
10b48b27b0 | |||
d08856c1fe | |||
0d108b043d | |||
a37245b7c8 | |||
19c4ebdda9 | |||
34d4b71f59 | |||
bd8794f646 | |||
e0adcd3277 | |||
e2fe615a31 | |||
0d2536fdfd | |||
c5813204d5 | |||
5064c39a94 | |||
1880f98fa1 | |||
d3c360d9e5 | |||
388c4b9653 | |||
87f1cf17c4 | |||
dae6493a3e | |||
fc0275314d | |||
c6fa19155b | |||
2fa0191d65 | |||
ad07984158 | |||
f909b86338 | |||
327df6529b | |||
658dc63c4c | |||
4edec5f666 | |||
d150a0c135 | |||
d4242781a0 | |||
7369ca0b25 | |||
561f427cc5 | |||
8049ab703a | |||
9c2a97263a | |||
345504c1a4 | |||
549f6f2077 | |||
35c6decc75 | |||
b3abeb78ff | |||
0562a1ad42 | |||
febb0920fd | |||
549662beb0 | |||
1ea4440c5d | |||
787abdff5b | |||
2237807241 | |||
e9d9d658c4 | |||
e704092d19 | |||
305f72c197 | |||
fb6b6b4476 | |||
791cc74dbb | |||
41f139589c | |||
df24e3020b | |||
e44c716cbe | |||
d35302923d | |||
4d928368bc | |||
c055d7a470 | |||
9e1b49e181 | |||
db6a9ede1b | |||
86df0a448e | |||
5ec052bd92 | |||
6f7984d05a | |||
f6d64d1d4b | |||
ef0c7a5a57 | |||
34dfbf8e9e | |||
71d38e6fd0 | |||
9a9ba2560b | |||
2432e51970 | |||
47434cd62d | |||
ff500b44a6 | |||
4c14c7f3a4 | |||
019c4bf182 | |||
2cbc291f04 | |||
5197a3a461 | |||
52be87785f | |||
8e19fb3a8c | |||
0448dcf655 | |||
b8f74ab9e7 | |||
501ce5cebb | |||
b896ca7ef6 | |||
d497db3010 | |||
24f95fdeaa | |||
d1c4818724 | |||
9f736a9d99 | |||
49cce6a968 | |||
713337130b | |||
0a73e7ac9f | |||
3344af72c2 | |||
41eb44137e | |||
94a9667d86 | |||
8b56a7defb | |||
5a4b9b4239 | |||
f37308461c | |||
9721098178 | |||
0ca5e67dad | |||
da94564d5e | |||
1f33237659 | |||
62e5979c13 | |||
8a1e18e087 | |||
a951daddce | |||
690f6d444a | |||
b733930745 | |||
f316a3000b | |||
ddae9dc6e1 | |||
0348d6558a | |||
6a497b32f6 | |||
47acc0ea90 | |||
967c952a4a | |||
b648d159dd | |||
aecd9387d9 | |||
6e8a5e1426 | |||
607899be56 | |||
5a92a8639a | |||
4cd629b5fc | |||
6020736430 | |||
14a4047bdd | |||
23c1e22a04 | |||
2a2ae4bc4f | |||
5f4812e1d0 | |||
3ab475d916 | |||
453d64eea5 | |||
17d33f4b19 | |||
c39a5933e1 | |||
a9636b5727 | |||
5e3f44dd87 | |||
1c64616ebd | |||
23273f53cc | |||
d11ce0a86e | |||
766ceda57a | |||
eb633c607e | |||
c72d56d02d | |||
e758c434ea | |||
90e3ae9457 | |||
0e825ffcfd | |||
8a19c71f62 | |||
5a7eff041a | |||
552459834a | |||
cc6325bf6a | |||
9597ea9e1f | |||
69b5670659 | |||
56fd436e5d | |||
b7558ae28c | |||
ea60c389be | |||
f6042f29f6 | |||
983882f5a0 | |||
a6d3fd92df | |||
96f39904b8 | |||
ee347aa7ef | |||
6437334e67 | |||
2f57d7f427 | |||
db07f564aa | |||
d1479a1b16 | |||
4d80e207da | |||
e7be7ac9b4 | |||
e0954c0f89 | |||
7ae061909c | |||
45a806f46b | |||
feb6b07657 | |||
1d98582d29 | |||
06663edba2 | |||
de0d1dc94d | |||
1652ea25e4 | |||
d794e3055c | |||
a92c68ac85 | |||
dd41789230 | |||
022401b60e | |||
ef218ff1ff | |||
f933bf2f40 | |||
4fc761adea | |||
d11c214d32 | |||
ffbbe5ca5f | |||
8582091219 | |||
28c8eb3ee6 | |||
3a00a5ac3d | |||
20035e0f1b | |||
67021b0e7c | |||
c5a2831665 | |||
768f073e49 | |||
504338ea66 | |||
a8c04f96d2 | |||
340faf5341 | |||
a76c39aff9 | |||
bb728a53cc | |||
5c28a7dd44 | |||
e1efb47543 | |||
e50a296a18 | |||
e211265c30 | |||
1f143a24db | |||
48f490b810 | |||
aed382de0c | |||
8ecf40a58b | |||
aca3c75e17 | |||
f28509608b | |||
ff6c508de7 | |||
7319ea2dcf | |||
6a4efaecb0 | |||
29b0eae43f | |||
9f3e742fb1 | |||
c8e09fea33 | |||
437e932471 | |||
ce07d71d23 | |||
9815c591e0 | |||
db7a3ab630 | |||
3fa772c32e | |||
6c9dc7a15b | |||
ece0429ea8 | |||
d56ddb16b1 | |||
b6267fdf28 | |||
1f190a9255 | |||
1f0fc0a6a2 | |||
3ba678851e | |||
0869ef3d0d | |||
91100ce1e2 | |||
a65ce47736 | |||
def17bbc1e | |||
eb7da8f414 | |||
9201fc1834 | |||
5385feb428 | |||
c6f29d9eb4 | |||
db557401aa | |||
c824af5bc3 | |||
1faba11a57 | |||
f0c72e8536 | |||
91f91b08e5 | |||
8faa909c32 | |||
49142fa80b | |||
2a6fccd22a | |||
1d10afa209 | |||
4b7c3c38cd | |||
440cacbafe | |||
b33bff92ee | |||
caed306346 | |||
d0eb6af7e9 | |||
ec5ed67f6c | |||
59b899ddff | |||
85784f796c | |||
4c0e19cbea | |||
b42eb9464f | |||
6559fdee15 | |||
3455bf3d27 | |||
0d96e68c1e | |||
29d3db5112 | |||
cdf88e4477 | |||
7caac1d0c7 | |||
45364d6553 | |||
2298eb124f | |||
6dff1f8e5e | |||
a944701f3a | |||
23866fe459 | |||
0a83b04419 | |||
e6ecdf8b1d | |||
2d48fe42f4 | |||
5894ccdaf2 | |||
79bec6f6b2 | |||
9610f96c11 | |||
36a326cd81 | |||
c0c222a0b8 | |||
e17f7020e6 | |||
6d9579d3e6 | |||
9f15ee8cb8 | |||
e892ed14da | |||
093a67525a | |||
1c62a3db6e | |||
c4b4c7134d | |||
82cb6d41b8 | |||
423380d987 | |||
175d97fdcf | |||
5dbbf970b0 | |||
1541d477af | |||
d745331654 | |||
defbdc5068 | |||
350f0d8365 | |||
b5c93fb3e3 | |||
5be45ebf8e | |||
ad8fe9fe81 | |||
c2f7edaa42 | |||
6821402fef | |||
8dbb0bd2c6 | |||
24a21c1761 | |||
0cad56ec73 | |||
4d8021c403 | |||
6573cbb16c | |||
bdf76bb4b7 | |||
74ce9cc6fd | |||
070a6d866e | |||
5e2d647a6c | |||
7beebe030d | |||
66f4a31b4c | |||
beddd6a460 | |||
faec866581 | |||
effed50cc1 | |||
38ad6096ad | |||
bd53042553 | |||
039d896dee | |||
ff2baf502b | |||
3b182ca223 | |||
8da8890a8e | |||
23023ec727 | |||
7d84a71a01 | |||
192001f193 | |||
63734682d2 | |||
a0cd2d55f8 | |||
a72c7adfc0 | |||
e88e02ec85 | |||
f7661c8bbd | |||
9add8479ca | |||
4c39e08dd4 | |||
44ce2ebece | |||
f5a8859d00 | |||
9ef0e8bc5f | |||
60eeafd111 | |||
6f3d6efa22 | |||
8d3275817b | |||
ca40d31dac | |||
438aac8879 | |||
2dfa6c2c82 | |||
c11435780d | |||
ee54328589 | |||
817d538b8f | |||
210775776f | |||
2a4ce75bc4 | |||
b26111fb42 | |||
e30103aa9f | |||
dc9203789e | |||
d70ce2776f | |||
ad7d65e903 | |||
67d54c5209 | |||
bb244b8338 | |||
fa04883ac1 | |||
6739ded5a9 | |||
9a7e5d934e | |||
6dc6d19d2d | |||
36cbc44ed6 | |||
0c591a50e3 | |||
7ee655a318 | |||
8447e9b9c2 | |||
09f92e5bad | |||
f9a419107a | |||
8f0572d11e | |||
7ebf793953 | |||
63783ee77b | |||
eba339ba27 | |||
0adb5a79f6 | |||
fa81adf254 | |||
558c7bba2a | |||
8cd1a42fb9 | |||
8cf0e78aa0 | |||
3f69a57013 | |||
f7f12cab10 | |||
cacaa378c8 | |||
33fe85eb96 | |||
a9744cbf48 | |||
b91d8a676c | |||
f19cd1c003 | |||
65341cecd0 | |||
c0cb891078 | |||
fc1c1a849a | |||
5a81ae956f | |||
0cac034512 | |||
5666995a15 | |||
8d3059e4f3 | |||
a90dc34494 | |||
2c6d82593e | |||
34bcc2df1a | |||
c00f2907ea | |||
b4d528a789 | |||
d9172cb296 | |||
bee36cde59 | |||
d4e7d9d64a | |||
7b0265207a | |||
7c076579fd | |||
7171706d7f | |||
9cd46ecbeb | |||
5f09ba675d | |||
630b926e2a | |||
9c6be60ad9 | |||
a0397fdcf4 | |||
59e13e8026 | |||
374b51e956 | |||
8faa1bf865 | |||
fc75867218 | |||
6d94c2c925 | |||
eb51dd1379 | |||
13a4559c37 | |||
4fcf7285d7 | |||
0ba9f25155 | |||
453c751c7f | |||
d1eaaef254 | |||
3eb466ff4b | |||
9f2529c886 | |||
fb25b28976 | |||
612163b82f | |||
3c43690a96 | |||
dd74565c7b | |||
fb69f67f47 | |||
18b48684eb | |||
098b0aef6e | |||
4ed8171130 | |||
335131affc | |||
bba17a8a67 | |||
082df0ec51 | |||
1883402b3d | |||
88a8b7d2fa | |||
987f03c4be | |||
1b3aacfa1d | |||
a03dde8a90 | |||
5f04a187ea | |||
2b68363452 | |||
3a994ab2a4 | |||
d7713357f4 | |||
e7c03fdb14 | |||
6105956847 | |||
89028f175a | |||
f121098957 | |||
4ff32af343 | |||
972868c15c | |||
0bc57f571b | |||
9de5b6f93e | |||
acf1ded1d4 | |||
a286f999e2 | |||
4b6c1da51d | |||
a81d5a3d41 | |||
4d17111233 | |||
64cb9812e0 | |||
ed037b2e3a | |||
d2be6a8e3a | |||
a9667eb0f4 | |||
7f3988f3c9 | |||
4c095a6f2a | |||
c10b5c3c8c | |||
9d920580a1 | |||
34ef4af799 | |||
5da47b69dd | |||
0e0dd2437b | |||
e42386b150 | |||
f21f81022e | |||
e73a468921 | |||
c0ac053380 | |||
4e670295d1 | |||
8d7d8d613c | |||
4d632a8679 | |||
ef219198d4 | |||
cc744dc581 | |||
47006fc9d2 | |||
ada53362d5 | |||
a03e48c5ce | |||
816b0c7d83 | |||
a6398f46da | |||
56babb2649 | |||
0edf4296c4 | |||
b8fdda50ec | |||
d25a051eae | |||
4a9b788703 | |||
d4ef321ac2 | |||
80c1dbdfbb | |||
b0af062d74 | |||
b4e75218f5 | |||
ab1840dd66 | |||
482491e93c | |||
2ca991ba3d | |||
b20c384f5a | |||
9ce8edbcd6 | |||
cb5b2148a3 | |||
d5702c6282 | |||
61a876b582 | |||
8c9748e4a0 | |||
6460245d5e | |||
b7979ad48e | |||
cbd95848e7 | |||
4704de937a | |||
394d8e99a4 | |||
a26f25ccd6 | |||
94257e0f50 | |||
b2a42a68a4 | |||
7895d59da3 | |||
b54c60d7af | |||
6bab3bf68e | |||
fdc09c658a | |||
a690a02f99 | |||
0e912fd647 | |||
27af330932 | |||
7187d28905 | |||
ca832b6090 | |||
53bd6bf06e | |||
813f271bdd | |||
63dc8fe7dc | |||
383f4e4dcf | |||
2896652fef | |||
cfe2648b62 | |||
8d49705c87 | |||
c99e6d8f2c | |||
0996bb500c | |||
3d4a45c93f | |||
0642af0b78 | |||
dce623dd7c | |||
646d174dd2 | |||
b8fdb82adc | |||
75d6cd1674 | |||
5c91658484 | |||
ebb44c992b | |||
233bb35ebe | |||
f60d0b9753 | |||
7e95c756b9 | |||
be26b92927 | |||
dd3ed1bfb9 | |||
6f56a61a64 | |||
2dee8034d3 | |||
d9d42020cc | |||
90298a2b6c | |||
7c17e7d52f | |||
fbb3ca98c1 | |||
220d21c3e0 | |||
84e74bc21e | |||
ec15060c84 | |||
334898ae23 | |||
b43df2ae27 | |||
a52638d898 | |||
5bc893b890 | |||
fe5d9e4cd2 | |||
a7442e0043 | |||
8103bbf9af | |||
056b90b590 | |||
70221e3d14 | |||
d570feffac | |||
3d52266773 | |||
7bdecd2ee6 | |||
a500ff28ac | |||
263bcae050 | |||
8691a79204 | |||
3b0b6dcf29 | |||
11f7935155 | |||
450a26d1b5 | |||
3e42c1bad4 | |||
5abbb7657b | |||
75b0fb3393 | |||
538c2ca4d3 | |||
5080840ed9 | |||
eded9bfb2d | |||
b3a43ae37c | |||
dc78746825 | |||
3c6828cbba | |||
26646264dc | |||
f7ecfdd4b6 | |||
967c80069b | |||
f8b0c071b7 | |||
221ab47410 | |||
ffe162214f | |||
ad9d8d26ed | |||
35402ada17 | |||
086a44bdbd | |||
6494a0352f | |||
ca1fb737a8 | |||
9e91a0a85d | |||
4e68fe2fea | |||
a36eab81eb | |||
215b2a3224 | |||
4c3f8e446f | |||
4b9922e5b1 | |||
6324521424 | |||
d6b18f2833 | |||
333e58ce2f | |||
699d3ca067 | |||
296779ddf1 | |||
8669f498f1 | |||
4de2ac3248 | |||
eb4dce91c3 | |||
c64a99345b | |||
2e174a1be5 | |||
11ef500475 | |||
d4fd6153c8 | |||
85b6bfbe5f | |||
5ddd138c97 | |||
5644d5f3f7 | |||
be06adcb59 | |||
4da350ebfc | |||
f391c33bdf | |||
18f450bd49 | |||
ee36b7f3eb | |||
f56d619243 | |||
a9a62bbfc8 | |||
ddd785898b | |||
8ba45a5f6a | |||
7d41e6227b | |||
1363226697 | |||
25910bb577 | |||
62e54a3a51 | |||
5f5b4c962b | |||
4a9a19eacb | |||
d4abf5621e | |||
1cb71b5217 | |||
a884f23855 | |||
421b003218 | |||
25a4310bb1 | |||
e897307548 | |||
0fd959c5c0 | |||
ce7d18798f | |||
be3b034cb8 | |||
9f674442d3 | |||
c21793943d | |||
ec67b60219 | |||
2fe553785e | |||
fd1d38f844 | |||
4d755dc0f6 | |||
30c65f9e61 | |||
3554406aa5 | |||
5eeaac1ad9 | |||
5a172abdb9 | |||
8f861d8ecb | |||
f9fdcd2d07 | |||
ed58f21a21 | |||
45af8eb4be | |||
88573105a0 | |||
f9469e3f99 | |||
26d92d9259 | |||
9cb0d37d51 | |||
5a25e1524a | |||
9e1a518689 | |||
cf5771dad3 | |||
db5aafed36 | |||
4b0324220a | |||
0183d2c880 | |||
c1fe18a261 | |||
ab2299ba1e | |||
2678b381b9 | |||
d3ef7920cb | |||
860269acf0 | |||
d2bd177b8f | |||
32cc03832a | |||
948d2cbdca | |||
22026f0755 | |||
a7a7b5aacb | |||
03d5b9e7e9 | |||
30c7e6c94c | |||
1ba96586f7 | |||
607f632515 | |||
58b46fbfcd | |||
9b53e26ab0 | |||
832d3175aa | |||
ebea8369d6 | |||
a8508aac99 | |||
59df02b3b8 | |||
f00657f217 | |||
110bc762a1 | |||
f35e5f79aa | |||
3f32109706 | |||
0f042f2e4a | |||
34d1eb140b | |||
62f67aabe3 | |||
82c3eaa0f9 | |||
31ede2ae1d | |||
54c672256f | |||
5f47d46b6f | |||
3f23bc0b85 | |||
366142382b | |||
ddbe0aaf13 | |||
75320bf579 | |||
15d8988569 | |||
84930b4924 | |||
1ede972222 | |||
cd1d1b4402 | |||
79caba45cc | |||
c101357051 | |||
9bebb82bbf | |||
d95d2ca7fe | |||
c0a883f76f | |||
eb6cfd22a7 | |||
254249e38b | |||
da28bb7d3c | |||
391c1ff911 | |||
1d475d0982 | |||
f92fa61101 | |||
ccca397a77 | |||
162fd26f32 | |||
1d7a235766 | |||
01a8deb77f | |||
cba770a551 | |||
c67afc4084 | |||
4ed30fa61e | |||
db16a0ffbe | |||
99ec355710 | |||
9e1882cebd | |||
80912cace0 | |||
0882894dc3 | |||
c1582147d7 | |||
ab8b37a899 | |||
9077eff34d | |||
2399fa456b | |||
c8c69a9a56 | |||
1258f3bba2 | |||
5488120e84 | |||
0b4ac54363 | |||
1a1434bfda | |||
1328c3e62c | |||
1800b62cd6 | |||
32fa4c9fcb | |||
15f0045a00 | |||
ac2211d9da | |||
cbd5b0dbfd | |||
8e4896d261 | |||
9481df619a | |||
d283a5236c | |||
6add88654e | |||
e4486b98fc | |||
778065f468 | |||
70794d79dd | |||
6e5ac4bffc | |||
4bab42fb58 | |||
c97823fe49 | |||
a3bb5d89cc | |||
f4f9f525d7 | |||
555525ea9d | |||
e455e20312 | |||
4c14e88a25 | |||
7561ea15de | |||
8242b09394 | |||
6f0fa731c0 | |||
576bb013ed | |||
aefedfb836 | |||
4295ddb671 | |||
9b9c0fe663 | |||
5a58f6ee64 | |||
da83c3af53 | |||
e84b17d550 | |||
b4fb0190a3 | |||
bb52b95e5b | |||
a2b5d667af | |||
2df9c0479d | |||
5c673dc7bb | |||
da2dd7daf4 | |||
f2a80030d7 | |||
918183f472 | |||
9da439623b | |||
957bb1c5ef | |||
677d46d7fd | |||
5af7baf36c | |||
8b2ca822f5 | |||
2303a97bb9 | |||
8be04cc013 | |||
9b6e47e6b8 | |||
677621989a | |||
0d5125db76 | |||
ed88f6594c | |||
b1816f2101 | |||
fe60c26e11 | |||
cca33a74b6 | |||
f977bf61eb | |||
f8f8a9bbb9 | |||
7a44d5768a | |||
d9e4219d70 | |||
6db5df1b31 | |||
e64ca4ab04 | |||
0e59ed62f5 | |||
dfe3394d4e | |||
9d4fb8048c | |||
a7a517733e | |||
e2f0a76309 | |||
07267ac425 | |||
8fb7620004 | |||
2ef85c4447 | |||
c3174ac044 | |||
952b48541c | |||
a97ffce5f9 | |||
5d514bd8c4 | |||
128234324d | |||
2d1bc2efcc | |||
2a1af96838 | |||
a6674440e6 | |||
5861d41ad3 | |||
fcd9c58a73 | |||
4bf2878cf7 | |||
79d508a020 | |||
03916b0b25 | |||
263964865c | |||
21f92b4a65 | |||
e38d03b304 | |||
f2b540ed8a | |||
79ad356d90 | |||
e70490481d | |||
66ab9504e9 | |||
009173fe23 | |||
75a5335f0f | |||
7a9452c66a | |||
82a999f95d | |||
0c2e9234bf | |||
964a3276a1 | |||
5185b027dc | |||
d690296120 | |||
9252a1f9d3 | |||
fc6742a17e | |||
31546da796 | |||
4a6c46a5c9 | |||
20262f3f4b | |||
dea61ef35e | |||
edda644e28 | |||
ee13ec1dca | |||
39bea1d5d0 | |||
453dcd790f | |||
bb70e6c81d | |||
4ff9db9d7e | |||
8b2e70d15d | |||
8e2f929933 | |||
ae2d86096b | |||
849c347e8c | |||
c974298836 | |||
b46eb7198b | |||
37db6764ab | |||
633296503d | |||
508cec2fd5 | |||
7a93614e4b | |||
4f319eaa4f | |||
86a8d00b3f | |||
5fe8c1f3d7 | |||
be91d893fb | |||
1fc6aa5a02 | |||
2256baced5 | |||
f2af904aeb | |||
030f612c38 | |||
d84ff2bbca | |||
4be238018b | |||
71c6313c46 | |||
f7daa7723d | |||
1ff35eef4c | |||
743bb3e98f | |||
83c4d5393c | |||
99008252f8 | |||
4cf00ed5cf | |||
8689444954 | |||
4210f692ff | |||
85a3578092 | |||
6b05d44d1f | |||
49b221ed68 | |||
67b43c223c | |||
5f9dc4395a | |||
bb8af2f19b | |||
996bd05ba6 | |||
ac03f5a97d | |||
a1a64e25ee | |||
53851efacb | |||
afea262e14 | |||
53f92f01da | |||
a267686098 | |||
9ee06b7d1f | |||
f53343141e | |||
62250f4ec6 | |||
485329130b | |||
6891c239e2 | |||
993c6472db | |||
123b0b2f05 | |||
487b1e4f34 | |||
b308cfa8d7 | |||
839884c65c | |||
dc93f5d4c9 | |||
735af9aaad | |||
9c52ee585f | |||
4c5f01020e | |||
fc315eb8da | |||
b90d8b14d6 | |||
1af49c930c | |||
624ae67b50 | |||
cd2fb49f9b | |||
3da531ede3 | |||
e3e4b2f818 | |||
98391da0d0 | |||
1555aed02f | |||
7a01529511 | |||
bc3e6b3962 | |||
7cbd5174f0 | |||
788cd401f6 | |||
bec8c8fe0a | |||
3184a64482 | |||
c7a83e6182 | |||
933919c647 | |||
7d3841e85f | |||
21e54d803f | |||
883af97148 | |||
3184019996 | |||
c0edaaf821 | |||
74ff9d04dd | |||
969902f503 | |||
04372e21dd | |||
0c53650216 | |||
8e028c2feb | |||
d75a864f0e | |||
81f3b133f6 | |||
b887916f5b | |||
2a354aa64f | |||
d9724e6885 | |||
d092e8e4bc | |||
e5b8975459 | |||
4f4784f4d8 | |||
51194cbf42 | |||
4d5a619cc0 | |||
2314340823 | |||
7c6b2c843b | |||
0c2b32da31 | |||
9ad4c736f1 | |||
0c0b9ca84a | |||
4154b62565 | |||
5a07d4ec66 | |||
64b758c8fa | |||
a0e29d42a6 | |||
0bbea79c64 | |||
467ad29656 | |||
d2fc1226f8 | |||
5c50a18b6f | |||
75505a2077 | |||
6d7525b5a1 | |||
4ca7ba427a | |||
740fafa86d | |||
4b80f52e11 | |||
7ae2bdc35f | |||
34473903dd | |||
86a4a7dcee | |||
73fe866cb6 | |||
8b95e9f97a | |||
a3eb72d160 | |||
b418db6ecf | |||
6cb1ab1d2b | |||
ae09dac720 | |||
44c9ad19a7 | |||
554272a927 | |||
acf2af8f66 | |||
b45a442447 | |||
75a720ead1 | |||
615ce287ce | |||
aa8d97249a | |||
2390df17f1 | |||
c022052539 | |||
13c050e2a6 | |||
ef371b3750 | |||
bb1f79347b | |||
6ed0d6d124 | |||
4ed60fe36b | |||
ca9fa79095 | |||
a2408cefcf | |||
145eaa5de3 | |||
1991c930f2 | |||
736f84b670 | |||
d4d5c2675b | |||
be232e2b77 | |||
42389188ad | |||
1f6af8c221 | |||
f4955e3e62 | |||
a8ef3096c1 | |||
14f76b2575 | |||
50065d37b9 | |||
a54670fb91 | |||
51fda51cbf | |||
53d0205e86 | |||
0f56d00959 | |||
b7a6fccdf9 | |||
522f49f48c | |||
e685f11514 | |||
1841b9b4c6 | |||
40e37a5c2c | |||
ac838645a9 | |||
be40d67c4d | |||
700cc06f45 |
@ -1,30 +1,18 @@
|
|||||||
[bumpversion]
|
[bumpversion]
|
||||||
current_version = 2022.3.2
|
current_version = 2022.8.2
|
||||||
tag = True
|
tag = True
|
||||||
commit = True
|
commit = True
|
||||||
parse = (?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)\-?(?P<release>.*)
|
parse = (?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)
|
||||||
serialize =
|
serialize = {major}.{minor}.{patch}
|
||||||
{major}.{minor}.{patch}-{release}
|
|
||||||
{major}.{minor}.{patch}
|
|
||||||
message = release: {new_version}
|
message = release: {new_version}
|
||||||
tag_name = version/{new_version}
|
tag_name = version/{new_version}
|
||||||
|
|
||||||
[bumpversion:part:release]
|
|
||||||
optional_value = stable
|
|
||||||
first_value = beta
|
|
||||||
values =
|
|
||||||
alpha
|
|
||||||
beta
|
|
||||||
stable
|
|
||||||
|
|
||||||
[bumpversion:file:pyproject.toml]
|
[bumpversion:file:pyproject.toml]
|
||||||
|
|
||||||
[bumpversion:file:docker-compose.yml]
|
[bumpversion:file:docker-compose.yml]
|
||||||
|
|
||||||
[bumpversion:file:schema.yml]
|
[bumpversion:file:schema.yml]
|
||||||
|
|
||||||
[bumpversion:file:.github/workflows/release-publish.yml]
|
|
||||||
|
|
||||||
[bumpversion:file:authentik/__init__.py]
|
[bumpversion:file:authentik/__init__.py]
|
||||||
|
|
||||||
[bumpversion:file:internal/constants/constants.go]
|
[bumpversion:file:internal/constants/constants.go]
|
||||||
|
92
.github/actions/comment-pr-instructions/action.yml
vendored
Normal file
92
.github/actions/comment-pr-instructions/action.yml
vendored
Normal file
@ -0,0 +1,92 @@
|
|||||||
|
name: 'Comment usage instructions on PRs'
|
||||||
|
description: 'Comment usage instructions on PRs'
|
||||||
|
|
||||||
|
inputs:
|
||||||
|
tag:
|
||||||
|
description: "Image tag to pull"
|
||||||
|
required: true
|
||||||
|
|
||||||
|
runs:
|
||||||
|
using: "composite"
|
||||||
|
steps:
|
||||||
|
- name: Generate config
|
||||||
|
id: ev
|
||||||
|
shell: python
|
||||||
|
run: |
|
||||||
|
"""Helper script to get the actual branch name, docker safe"""
|
||||||
|
import os
|
||||||
|
from time import time
|
||||||
|
|
||||||
|
env_pr_branch = "GITHUB_HEAD_REF"
|
||||||
|
default_branch = "GITHUB_REF"
|
||||||
|
sha = "GITHUB_SHA"
|
||||||
|
|
||||||
|
branch_name = os.environ[default_branch]
|
||||||
|
if os.environ.get(env_pr_branch, "") != "":
|
||||||
|
branch_name = os.environ[env_pr_branch]
|
||||||
|
|
||||||
|
should_build = str(os.environ.get("DOCKER_USERNAME", "") != "").lower()
|
||||||
|
|
||||||
|
print("##[set-output name=branchName]%s" % branch_name)
|
||||||
|
print(
|
||||||
|
"##[set-output name=branchNameContainer]%s"
|
||||||
|
% branch_name.replace("refs/heads/", "").replace("/", "-")
|
||||||
|
)
|
||||||
|
print("##[set-output name=timestamp]%s" % int(time()))
|
||||||
|
print("##[set-output name=sha]%s" % os.environ[sha])
|
||||||
|
print("##[set-output name=shouldBuild]%s" % should_build)
|
||||||
|
|
||||||
|
import configparser
|
||||||
|
parser = configparser.ConfigParser()
|
||||||
|
parser.read(".bumpversion.cfg")
|
||||||
|
version = parser.get("bumpversion", "current_version")
|
||||||
|
version_family = ".".join(version.split(".")[:-1])
|
||||||
|
print("##[set-output name=version]%s" % version)
|
||||||
|
print("##[set-output name=versionFamily]%s" % version_family)
|
||||||
|
- name: Find Comment
|
||||||
|
uses: peter-evans/find-comment@v2
|
||||||
|
id: fc
|
||||||
|
with:
|
||||||
|
issue-number: ${{ github.event.pull_request.number }}
|
||||||
|
comment-author: 'github-actions[bot]'
|
||||||
|
body-includes: authentik PR Installation instructions
|
||||||
|
- name: Create or update comment
|
||||||
|
uses: peter-evans/create-or-update-comment@v2
|
||||||
|
with:
|
||||||
|
comment-id: ${{ steps.fc.outputs.comment-id }}
|
||||||
|
issue-number: ${{ github.event.pull_request.number }}
|
||||||
|
body: |
|
||||||
|
authentik PR Installation instructions
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Instructions for docker-compose</summary>
|
||||||
|
|
||||||
|
Add the following block to your `.env` file:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
AUTHENTIK_IMAGE=ghcr.io/goauthentik/dev-server
|
||||||
|
AUTHENTIK_TAG=${{ inputs.tag }}
|
||||||
|
AUTHENTIK_OUTPOSTS__CONTAINER_IMAGE_BASE=ghcr.io/goauthentik/dev-%(type)s:gh-%(build_hash)s
|
||||||
|
```
|
||||||
|
|
||||||
|
Afterwards, run the upgrade commands from the latest release notes.
|
||||||
|
</details>
|
||||||
|
<details>
|
||||||
|
<summary>Instructions for Kubernetes</summary>
|
||||||
|
|
||||||
|
Add the following block to your `values.yml` file:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
authentik:
|
||||||
|
outposts:
|
||||||
|
container_image_base: ghcr.io/goauthentik/dev-%(type)s:gh-%(build_hash)s
|
||||||
|
image:
|
||||||
|
repository: ghcr.io/goauthentik/dev-server
|
||||||
|
tag: ${{ inputs.tag }}
|
||||||
|
# pullPolicy: Always to ensure you always get the latest version
|
||||||
|
pullPolicy: Always
|
||||||
|
```
|
||||||
|
|
||||||
|
Afterwards, run the upgrade commands from the latest release notes.
|
||||||
|
</details>
|
||||||
|
edit-mode: replace
|
63
.github/actions/docker-push-variables/action.yml
vendored
Normal file
63
.github/actions/docker-push-variables/action.yml
vendored
Normal file
@ -0,0 +1,63 @@
|
|||||||
|
name: 'Prepare docker environment variables'
|
||||||
|
description: 'Prepare docker environment variables'
|
||||||
|
|
||||||
|
outputs:
|
||||||
|
shouldBuild:
|
||||||
|
description: "Whether to build image or not"
|
||||||
|
value: ${{ steps.ev.outputs.shouldBuild }}
|
||||||
|
branchName:
|
||||||
|
description: "Branch name"
|
||||||
|
value: ${{ steps.ev.outputs.branchName }}
|
||||||
|
branchNameContainer:
|
||||||
|
description: "Branch name (for containers)"
|
||||||
|
value: ${{ steps.ev.outputs.branchNameContainer }}
|
||||||
|
timestamp:
|
||||||
|
description: "Timestamp"
|
||||||
|
value: ${{ steps.ev.outputs.timestamp }}
|
||||||
|
sha:
|
||||||
|
description: "sha"
|
||||||
|
value: ${{ steps.ev.outputs.sha }}
|
||||||
|
version:
|
||||||
|
description: "version"
|
||||||
|
value: ${{ steps.ev.outputs.version }}
|
||||||
|
versionFamily:
|
||||||
|
description: "versionFamily"
|
||||||
|
value: ${{ steps.ev.outputs.versionFamily }}
|
||||||
|
|
||||||
|
runs:
|
||||||
|
using: "composite"
|
||||||
|
steps:
|
||||||
|
- name: Generate config
|
||||||
|
id: ev
|
||||||
|
shell: python
|
||||||
|
run: |
|
||||||
|
"""Helper script to get the actual branch name, docker safe"""
|
||||||
|
import os
|
||||||
|
from time import time
|
||||||
|
|
||||||
|
env_pr_branch = "GITHUB_HEAD_REF"
|
||||||
|
default_branch = "GITHUB_REF"
|
||||||
|
sha = "GITHUB_SHA"
|
||||||
|
|
||||||
|
branch_name = os.environ[default_branch]
|
||||||
|
if os.environ.get(env_pr_branch, "") != "":
|
||||||
|
branch_name = os.environ[env_pr_branch]
|
||||||
|
|
||||||
|
should_build = str(os.environ.get("DOCKER_USERNAME", "") != "").lower()
|
||||||
|
|
||||||
|
print("##[set-output name=branchName]%s" % branch_name)
|
||||||
|
print(
|
||||||
|
"##[set-output name=branchNameContainer]%s"
|
||||||
|
% branch_name.replace("refs/heads/", "").replace("/", "-")
|
||||||
|
)
|
||||||
|
print("##[set-output name=timestamp]%s" % int(time()))
|
||||||
|
print("##[set-output name=sha]%s" % os.environ[sha])
|
||||||
|
print("##[set-output name=shouldBuild]%s" % should_build)
|
||||||
|
|
||||||
|
import configparser
|
||||||
|
parser = configparser.ConfigParser()
|
||||||
|
parser.read(".bumpversion.cfg")
|
||||||
|
version = parser.get("bumpversion", "current_version")
|
||||||
|
version_family = ".".join(version.split(".")[:-1])
|
||||||
|
print("##[set-output name=version]%s" % version)
|
||||||
|
print("##[set-output name=versionFamily]%s" % version_family)
|
45
.github/actions/setup/action.yml
vendored
Normal file
45
.github/actions/setup/action.yml
vendored
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
name: 'Setup authentik testing environemnt'
|
||||||
|
description: 'Setup authentik testing environemnt'
|
||||||
|
|
||||||
|
runs:
|
||||||
|
using: "composite"
|
||||||
|
steps:
|
||||||
|
- name: Install poetry
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
pipx install poetry || true
|
||||||
|
sudo apt update
|
||||||
|
sudo apt install -y libxmlsec1-dev pkg-config gettext
|
||||||
|
- name: Setup python and restore poetry
|
||||||
|
uses: actions/setup-python@v3
|
||||||
|
with:
|
||||||
|
python-version: '3.10'
|
||||||
|
cache: 'poetry'
|
||||||
|
- name: Setup node
|
||||||
|
uses: actions/setup-node@v3.1.0
|
||||||
|
with:
|
||||||
|
node-version: '16'
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: web/package-lock.json
|
||||||
|
- name: Setup dependencies
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
docker-compose -f .github/actions/setup/docker-compose.yml up -d
|
||||||
|
poetry env use python3.10
|
||||||
|
poetry install
|
||||||
|
npm install -g pyright@1.1.136
|
||||||
|
- name: Generate config
|
||||||
|
shell: poetry run python {0}
|
||||||
|
run: |
|
||||||
|
from authentik.lib.generators import generate_id
|
||||||
|
from yaml import safe_dump
|
||||||
|
|
||||||
|
with open("local.env.yml", "w") as _config:
|
||||||
|
safe_dump(
|
||||||
|
{
|
||||||
|
"log_level": "debug",
|
||||||
|
"secret_key": generate_id(),
|
||||||
|
},
|
||||||
|
_config,
|
||||||
|
default_flow_style=False,
|
||||||
|
)
|
108
.github/dependabot.yml
vendored
108
.github/dependabot.yml
vendored
@ -1,50 +1,62 @@
|
|||||||
version: 2
|
version: 2
|
||||||
updates:
|
updates:
|
||||||
- package-ecosystem: "github-actions"
|
- package-ecosystem: "github-actions"
|
||||||
directory: "/"
|
directory: "/"
|
||||||
schedule:
|
schedule:
|
||||||
interval: daily
|
interval: daily
|
||||||
time: "04:00"
|
time: "04:00"
|
||||||
open-pull-requests-limit: 10
|
open-pull-requests-limit: 10
|
||||||
assignees:
|
reviewers:
|
||||||
- BeryJu
|
- "@goauthentik/core"
|
||||||
- package-ecosystem: gomod
|
commit-message:
|
||||||
directory: "/"
|
prefix: "ci:"
|
||||||
schedule:
|
- package-ecosystem: gomod
|
||||||
interval: daily
|
directory: "/"
|
||||||
time: "04:00"
|
schedule:
|
||||||
open-pull-requests-limit: 10
|
interval: daily
|
||||||
assignees:
|
time: "04:00"
|
||||||
- BeryJu
|
open-pull-requests-limit: 10
|
||||||
- package-ecosystem: npm
|
reviewers:
|
||||||
directory: "/web"
|
- "@goauthentik/core"
|
||||||
schedule:
|
commit-message:
|
||||||
interval: daily
|
prefix: "core:"
|
||||||
time: "04:00"
|
- package-ecosystem: npm
|
||||||
open-pull-requests-limit: 10
|
directory: "/web"
|
||||||
assignees:
|
schedule:
|
||||||
- BeryJu
|
interval: daily
|
||||||
- package-ecosystem: npm
|
time: "04:00"
|
||||||
directory: "/website"
|
open-pull-requests-limit: 10
|
||||||
schedule:
|
reviewers:
|
||||||
interval: daily
|
- "@goauthentik/core"
|
||||||
time: "04:00"
|
commit-message:
|
||||||
open-pull-requests-limit: 10
|
prefix: "web:"
|
||||||
assignees:
|
- package-ecosystem: npm
|
||||||
- BeryJu
|
directory: "/website"
|
||||||
- package-ecosystem: pip
|
schedule:
|
||||||
directory: "/"
|
interval: daily
|
||||||
schedule:
|
time: "04:00"
|
||||||
interval: daily
|
open-pull-requests-limit: 10
|
||||||
time: "04:00"
|
reviewers:
|
||||||
open-pull-requests-limit: 10
|
- "@goauthentik/core"
|
||||||
assignees:
|
commit-message:
|
||||||
- BeryJu
|
prefix: "website:"
|
||||||
- package-ecosystem: docker
|
- package-ecosystem: pip
|
||||||
directory: "/"
|
directory: "/"
|
||||||
schedule:
|
schedule:
|
||||||
interval: daily
|
interval: daily
|
||||||
time: "04:00"
|
time: "04:00"
|
||||||
open-pull-requests-limit: 10
|
open-pull-requests-limit: 10
|
||||||
assignees:
|
reviewers:
|
||||||
- BeryJu
|
- "@goauthentik/core"
|
||||||
|
commit-message:
|
||||||
|
prefix: "core:"
|
||||||
|
- package-ecosystem: docker
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: daily
|
||||||
|
time: "04:00"
|
||||||
|
open-pull-requests-limit: 10
|
||||||
|
reviewers:
|
||||||
|
- "@goauthentik/core"
|
||||||
|
commit-message:
|
||||||
|
prefix: "core:"
|
||||||
|
2
.github/pull_request_template.md
vendored
2
.github/pull_request_template.md
vendored
@ -1,7 +1,7 @@
|
|||||||
<!--
|
<!--
|
||||||
👋 Hello there! Welcome.
|
👋 Hello there! Welcome.
|
||||||
|
|
||||||
Please check the [Contributing guidelines](https://github.com/goauthentik/authentik/blob/master/CONTRIBUTING.md#how-can-i-contribute).
|
Please check the [Contributing guidelines](https://github.com/goauthentik/authentik/blob/main/CONTRIBUTING.md#how-can-i-contribute).
|
||||||
-->
|
-->
|
||||||
|
|
||||||
# Details
|
# Details
|
||||||
|
3
.github/stale.yml
vendored
3
.github/stale.yml
vendored
@ -8,6 +8,9 @@ exemptLabels:
|
|||||||
- security
|
- security
|
||||||
- pr_wanted
|
- pr_wanted
|
||||||
- enhancement
|
- enhancement
|
||||||
|
- bug/confirmed
|
||||||
|
- enhancement/confirmed
|
||||||
|
- question
|
||||||
# Comment to post when marking an issue as stale. Set to `false` to disable
|
# Comment to post when marking an issue as stale. Set to `false` to disable
|
||||||
markComment: >
|
markComment: >
|
||||||
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
|
||||||
|
166
.github/workflows/ci-main.yml
vendored
166
.github/workflows/ci-main.yml
vendored
@ -3,14 +3,14 @@ name: authentik-ci-main
|
|||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- master
|
- main
|
||||||
- next
|
- next
|
||||||
- version-*
|
- version-*
|
||||||
paths-ignore:
|
paths-ignore:
|
||||||
- website
|
- website
|
||||||
pull_request:
|
pull_request:
|
||||||
branches:
|
branches:
|
||||||
- master
|
- main
|
||||||
|
|
||||||
env:
|
env:
|
||||||
POSTGRES_DB: authentik
|
POSTGRES_DB: authentik
|
||||||
@ -32,35 +32,16 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-python@v3
|
- name: Setup authentik env
|
||||||
- uses: actions/setup-node@v3.0.0
|
uses: ./.github/actions/setup
|
||||||
with:
|
|
||||||
node-version: '16'
|
|
||||||
- id: cache-poetry
|
|
||||||
uses: actions/cache@v2.1.7
|
|
||||||
with:
|
|
||||||
path: ~/.cache/pypoetry/virtualenvs
|
|
||||||
key: ${{ runner.os }}-poetry-cache-v2-${{ hashFiles('**/poetry.lock') }}
|
|
||||||
- name: prepare
|
|
||||||
env:
|
|
||||||
INSTALL: ${{ steps.cache-poetry.outputs.cache-hit }}
|
|
||||||
run: scripts/ci_prepare.sh
|
|
||||||
- name: run job
|
- name: run job
|
||||||
run: poetry run make ci-${{ matrix.job }}
|
run: poetry run make ci-${{ matrix.job }}
|
||||||
test-migrations:
|
test-migrations:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-python@v3
|
- name: Setup authentik env
|
||||||
- id: cache-poetry
|
uses: ./.github/actions/setup
|
||||||
uses: actions/cache@v2.1.7
|
|
||||||
with:
|
|
||||||
path: ~/.cache/pypoetry/virtualenvs
|
|
||||||
key: ${{ runner.os }}-poetry-cache-v2-${{ hashFiles('**/poetry.lock') }}
|
|
||||||
- name: prepare
|
|
||||||
env:
|
|
||||||
INSTALL: ${{ steps.cache-poetry.outputs.cache-hit }}
|
|
||||||
run: scripts/ci_prepare.sh
|
|
||||||
- name: run migrations
|
- name: run migrations
|
||||||
run: poetry run python -m lifecycle.migrate
|
run: poetry run python -m lifecycle.migrate
|
||||||
test-migrations-from-stable:
|
test-migrations-from-stable:
|
||||||
@ -69,17 +50,8 @@ jobs:
|
|||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
- uses: actions/setup-python@v3
|
- name: Setup authentik env
|
||||||
- name: prepare variables
|
uses: ./.github/actions/setup
|
||||||
id: ev
|
|
||||||
run: |
|
|
||||||
python ./scripts/gh_env.py
|
|
||||||
sudo pip install -U pipenv
|
|
||||||
- id: cache-poetry
|
|
||||||
uses: actions/cache@v2.1.7
|
|
||||||
with:
|
|
||||||
path: ~/.cache/pypoetry/virtualenvs
|
|
||||||
key: ${{ runner.os }}-poetry-cache-v2-${{ hashFiles('**/poetry.lock') }}
|
|
||||||
- name: checkout stable
|
- name: checkout stable
|
||||||
run: |
|
run: |
|
||||||
# Copy current, latest config to local
|
# Copy current, latest config to local
|
||||||
@ -89,13 +61,8 @@ jobs:
|
|||||||
git checkout $(git describe --abbrev=0 --match 'version/*')
|
git checkout $(git describe --abbrev=0 --match 'version/*')
|
||||||
rm -rf .github/ scripts/
|
rm -rf .github/ scripts/
|
||||||
mv ../.github ../scripts .
|
mv ../.github ../scripts .
|
||||||
- name: prepare
|
- name: Setup authentik env (ensure stable deps are installed)
|
||||||
env:
|
uses: ./.github/actions/setup
|
||||||
INSTALL: ${{ steps.cache-poetry.outputs.cache-hit }}
|
|
||||||
run: |
|
|
||||||
scripts/ci_prepare.sh
|
|
||||||
# install anyways since stable will have different dependencies
|
|
||||||
poetry install
|
|
||||||
- name: run migrations to stable
|
- name: run migrations to stable
|
||||||
run: poetry run python -m lifecycle.migrate
|
run: poetry run python -m lifecycle.migrate
|
||||||
- name: checkout current code
|
- name: checkout current code
|
||||||
@ -103,28 +70,19 @@ jobs:
|
|||||||
set -x
|
set -x
|
||||||
git fetch
|
git fetch
|
||||||
git reset --hard HEAD
|
git reset --hard HEAD
|
||||||
|
git clean -d -fx .
|
||||||
git checkout $GITHUB_SHA
|
git checkout $GITHUB_SHA
|
||||||
poetry install
|
poetry install
|
||||||
- name: prepare
|
- name: Setup authentik env (ensure latest deps are installed)
|
||||||
env:
|
uses: ./.github/actions/setup
|
||||||
INSTALL: ${{ steps.cache-poetry.outputs.cache-hit }}
|
|
||||||
run: scripts/ci_prepare.sh
|
|
||||||
- name: migrate to latest
|
- name: migrate to latest
|
||||||
run: poetry run python -m lifecycle.migrate
|
run: poetry run python -m lifecycle.migrate
|
||||||
test-unittest:
|
test-unittest:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-python@v3
|
- name: Setup authentik env
|
||||||
- id: cache-poetry
|
uses: ./.github/actions/setup
|
||||||
uses: actions/cache@v2.1.7
|
|
||||||
with:
|
|
||||||
path: ~/.cache/pypoetry/virtualenvs
|
|
||||||
key: ${{ runner.os }}-poetry-cache-v2-${{ hashFiles('**/poetry.lock') }}
|
|
||||||
- name: prepare
|
|
||||||
env:
|
|
||||||
INSTALL: ${{ steps.cache-poetry.outputs.cache-hit }}
|
|
||||||
run: scripts/ci_prepare.sh
|
|
||||||
- uses: testspace-com/setup-testspace@v1
|
- uses: testspace-com/setup-testspace@v1
|
||||||
with:
|
with:
|
||||||
domain: ${{github.repository_owner}}
|
domain: ${{github.repository_owner}}
|
||||||
@ -137,26 +95,18 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
testspace [unittest]unittest.xml --link=codecov
|
testspace [unittest]unittest.xml --link=codecov
|
||||||
- if: ${{ always() }}
|
- if: ${{ always() }}
|
||||||
uses: codecov/codecov-action@v2
|
uses: codecov/codecov-action@v3
|
||||||
test-integration:
|
test-integration:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-python@v3
|
- name: Setup authentik env
|
||||||
- id: cache-poetry
|
uses: ./.github/actions/setup
|
||||||
uses: actions/cache@v2.1.7
|
|
||||||
with:
|
|
||||||
path: ~/.cache/pypoetry/virtualenvs
|
|
||||||
key: ${{ runner.os }}-poetry-cache-v2-${{ hashFiles('**/poetry.lock') }}
|
|
||||||
- name: prepare
|
|
||||||
env:
|
|
||||||
INSTALL: ${{ steps.cache-poetry.outputs.cache-hit }}
|
|
||||||
run: scripts/ci_prepare.sh
|
|
||||||
- uses: testspace-com/setup-testspace@v1
|
- uses: testspace-com/setup-testspace@v1
|
||||||
with:
|
with:
|
||||||
domain: ${{github.repository_owner}}
|
domain: ${{github.repository_owner}}
|
||||||
- name: Create k8s Kind Cluster
|
- name: Create k8s Kind Cluster
|
||||||
uses: helm/kind-action@v1.2.0
|
uses: helm/kind-action@v1.3.0
|
||||||
- name: run integration
|
- name: run integration
|
||||||
run: |
|
run: |
|
||||||
poetry run make test-integration
|
poetry run make test-integration
|
||||||
@ -166,41 +116,30 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
testspace [integration]unittest.xml --link=codecov
|
testspace [integration]unittest.xml --link=codecov
|
||||||
- if: ${{ always() }}
|
- if: ${{ always() }}
|
||||||
uses: codecov/codecov-action@v2
|
uses: codecov/codecov-action@v3
|
||||||
test-e2e-provider:
|
test-e2e-provider:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-python@v3
|
- name: Setup authentik env
|
||||||
- uses: actions/setup-node@v3.0.0
|
uses: ./.github/actions/setup
|
||||||
with:
|
|
||||||
node-version: '16'
|
|
||||||
cache: 'npm'
|
|
||||||
cache-dependency-path: web/package-lock.json
|
|
||||||
- uses: testspace-com/setup-testspace@v1
|
- uses: testspace-com/setup-testspace@v1
|
||||||
with:
|
with:
|
||||||
domain: ${{github.repository_owner}}
|
domain: ${{github.repository_owner}}
|
||||||
- id: cache-poetry
|
- name: Setup authentik env
|
||||||
uses: actions/cache@v2.1.7
|
|
||||||
with:
|
|
||||||
path: ~/.cache/pypoetry/virtualenvs
|
|
||||||
key: ${{ runner.os }}-poetry-cache-v2-${{ hashFiles('**/poetry.lock') }}
|
|
||||||
- name: prepare
|
|
||||||
env:
|
|
||||||
INSTALL: ${{ steps.cache-poetry.outputs.cache-hit }}
|
|
||||||
run: |
|
run: |
|
||||||
scripts/ci_prepare.sh
|
|
||||||
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@v2.1.7
|
uses: actions/cache@v3
|
||||||
with:
|
with:
|
||||||
path: web/dist
|
path: web/dist
|
||||||
key: ${{ runner.os }}-web-${{ hashFiles('web/package-lock.json', 'web/**') }}
|
key: ${{ runner.os }}-web-${{ hashFiles('web/package-lock.json', 'web/src/**') }}
|
||||||
- name: prepare web ui
|
- name: prepare web ui
|
||||||
if: steps.cache-web.outputs.cache-hit != 'true'
|
if: steps.cache-web.outputs.cache-hit != 'true'
|
||||||
|
working-directory: web
|
||||||
run: |
|
run: |
|
||||||
cd web
|
npm ci
|
||||||
npm i
|
make -C .. gen-client-ts
|
||||||
npm run build
|
npm run build
|
||||||
- name: run e2e
|
- name: run e2e
|
||||||
run: |
|
run: |
|
||||||
@ -211,41 +150,30 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
testspace [e2e-provider]unittest.xml --link=codecov
|
testspace [e2e-provider]unittest.xml --link=codecov
|
||||||
- if: ${{ always() }}
|
- if: ${{ always() }}
|
||||||
uses: codecov/codecov-action@v2
|
uses: codecov/codecov-action@v3
|
||||||
test-e2e-rest:
|
test-e2e-rest:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-python@v3
|
- name: Setup authentik env
|
||||||
- uses: actions/setup-node@v3.0.0
|
uses: ./.github/actions/setup
|
||||||
with:
|
|
||||||
node-version: '16'
|
|
||||||
cache: 'npm'
|
|
||||||
cache-dependency-path: web/package-lock.json
|
|
||||||
- uses: testspace-com/setup-testspace@v1
|
- uses: testspace-com/setup-testspace@v1
|
||||||
with:
|
with:
|
||||||
domain: ${{github.repository_owner}}
|
domain: ${{github.repository_owner}}
|
||||||
- id: cache-poetry
|
- name: Setup authentik env
|
||||||
uses: actions/cache@v2.1.7
|
|
||||||
with:
|
|
||||||
path: ~/.cache/pypoetry/virtualenvs
|
|
||||||
key: ${{ runner.os }}-poetry-cache-v2-${{ hashFiles('**/poetry.lock') }}
|
|
||||||
- name: prepare
|
|
||||||
env:
|
|
||||||
INSTALL: ${{ steps.cache-poetry.outputs.cache-hit }}
|
|
||||||
run: |
|
run: |
|
||||||
scripts/ci_prepare.sh
|
|
||||||
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@v2.1.7
|
uses: actions/cache@v3
|
||||||
with:
|
with:
|
||||||
path: web/dist
|
path: web/dist
|
||||||
key: ${{ runner.os }}-web-${{ hashFiles('web/package-lock.json', 'web/**') }}
|
key: ${{ runner.os }}-web-${{ hashFiles('web/package-lock.json', 'web/src/**') }}
|
||||||
- name: prepare web ui
|
- name: prepare web ui
|
||||||
if: steps.cache-web.outputs.cache-hit != 'true'
|
if: steps.cache-web.outputs.cache-hit != 'true'
|
||||||
|
working-directory: web/
|
||||||
run: |
|
run: |
|
||||||
cd web
|
npm ci
|
||||||
npm i
|
make -C .. gen-client-ts
|
||||||
npm run build
|
npm run build
|
||||||
- name: run e2e
|
- name: run e2e
|
||||||
run: |
|
run: |
|
||||||
@ -256,7 +184,7 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
testspace [e2e-rest]unittest.xml --link=codecov
|
testspace [e2e-rest]unittest.xml --link=codecov
|
||||||
- if: ${{ always() }}
|
- if: ${{ always() }}
|
||||||
uses: codecov/codecov-action@v2
|
uses: codecov/codecov-action@v3
|
||||||
ci-core-mark:
|
ci-core-mark:
|
||||||
needs:
|
needs:
|
||||||
- lint
|
- lint
|
||||||
@ -281,24 +209,23 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@v1.2.0
|
uses: docker/setup-qemu-action@v2.0.0
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v1
|
uses: docker/setup-buildx-action@v2
|
||||||
- name: prepare variables
|
- name: prepare variables
|
||||||
|
uses: ./.github/actions/docker-push-variables
|
||||||
id: ev
|
id: ev
|
||||||
env:
|
env:
|
||||||
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
||||||
run: |
|
|
||||||
python ./scripts/gh_env.py
|
|
||||||
- name: Login to Container Registry
|
- name: Login to Container Registry
|
||||||
uses: docker/login-action@v1
|
uses: docker/login-action@v2
|
||||||
if: ${{ steps.ev.outputs.shouldBuild == 'true' }}
|
if: ${{ steps.ev.outputs.shouldBuild == 'true' }}
|
||||||
with:
|
with:
|
||||||
registry: ghcr.io
|
registry: ghcr.io
|
||||||
username: ${{ github.repository_owner }}
|
username: ${{ github.repository_owner }}
|
||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
- name: Building Docker Image
|
- name: Building Docker Image
|
||||||
uses: docker/build-push-action@v2
|
uses: docker/build-push-action@v3
|
||||||
with:
|
with:
|
||||||
push: ${{ steps.ev.outputs.shouldBuild == 'true' }}
|
push: ${{ steps.ev.outputs.shouldBuild == 'true' }}
|
||||||
tags: |
|
tags: |
|
||||||
@ -306,4 +233,11 @@ jobs:
|
|||||||
ghcr.io/goauthentik/dev-server:gh-${{ steps.ev.outputs.branchNameContainer }}-${{ steps.ev.outputs.timestamp }}-${{ steps.ev.outputs.sha }}
|
ghcr.io/goauthentik/dev-server:gh-${{ steps.ev.outputs.branchNameContainer }}-${{ steps.ev.outputs.timestamp }}-${{ steps.ev.outputs.sha }}
|
||||||
build-args: |
|
build-args: |
|
||||||
GIT_BUILD_HASH=${{ steps.ev.outputs.sha }}
|
GIT_BUILD_HASH=${{ steps.ev.outputs.sha }}
|
||||||
|
VERSION_FAMILY=${{ steps.ev.outputs.versionFamily }}
|
||||||
platforms: ${{ matrix.arch }}
|
platforms: ${{ matrix.arch }}
|
||||||
|
- name: Comment on PR
|
||||||
|
if: github.event_name == 'pull_request'
|
||||||
|
continue-on-error: true
|
||||||
|
uses: ./.github/actions/comment-pr-instructions
|
||||||
|
with:
|
||||||
|
tag: gh-${{ steps.ev.outputs.branchNameContainer }}
|
||||||
|
55
.github/workflows/ci-outpost.yml
vendored
55
.github/workflows/ci-outpost.yml
vendored
@ -3,48 +3,43 @@ name: authentik-ci-outpost
|
|||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- master
|
- main
|
||||||
- next
|
- next
|
||||||
- version-*
|
- version-*
|
||||||
pull_request:
|
pull_request:
|
||||||
branches:
|
branches:
|
||||||
- master
|
- main
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
lint-golint:
|
lint-golint:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-go@v2
|
- uses: actions/setup-go@v3
|
||||||
with:
|
with:
|
||||||
go-version: "^1.17"
|
go-version: "^1.17"
|
||||||
- name: Run linter
|
- name: Prepare and generate API
|
||||||
run: |
|
run: |
|
||||||
# Create folder structure for go embeds
|
# Create folder structure for go embeds
|
||||||
mkdir -p web/dist
|
mkdir -p web/dist
|
||||||
mkdir -p website/help
|
mkdir -p website/help
|
||||||
touch web/dist/test website/help/test
|
touch web/dist/test website/help/test
|
||||||
docker run \
|
- name: Generate API
|
||||||
--rm \
|
run: make gen-client-go
|
||||||
-v $(pwd):/app \
|
- name: golangci-lint
|
||||||
-w /app \
|
uses: golangci/golangci-lint-action@v3
|
||||||
golangci/golangci-lint:v1.43 \
|
|
||||||
golangci-lint run -v --timeout 200s
|
|
||||||
test-unittest:
|
test-unittest:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-go@v2
|
- uses: actions/setup-go@v3
|
||||||
with:
|
with:
|
||||||
go-version: "^1.17"
|
go-version: "^1.17"
|
||||||
- name: Get dependencies
|
- name: Generate API
|
||||||
run: |
|
run: make gen-client-go
|
||||||
go get github.com/axw/gocov/gocov
|
|
||||||
go get github.com/AlekSi/gocov-xml
|
|
||||||
go get github.com/jstemmer/go-junit-report
|
|
||||||
- name: Go unittests
|
- name: Go unittests
|
||||||
run: |
|
run: |
|
||||||
go test -timeout 0 -v -race -coverprofile=coverage.out -covermode=atomic -cover ./... | go-junit-report > junit.xml
|
go test -timeout 0 -v -race -coverprofile=coverage.out -covermode=atomic -cover ./...
|
||||||
ci-outpost-mark:
|
ci-outpost-mark:
|
||||||
needs:
|
needs:
|
||||||
- lint-golint
|
- lint-golint
|
||||||
@ -68,24 +63,25 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@v1.2.0
|
uses: docker/setup-qemu-action@v2.0.0
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v1
|
uses: docker/setup-buildx-action@v2
|
||||||
- name: prepare variables
|
- name: prepare variables
|
||||||
|
uses: ./.github/actions/docker-push-variables
|
||||||
id: ev
|
id: ev
|
||||||
env:
|
env:
|
||||||
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
||||||
run: |
|
|
||||||
python ./scripts/gh_env.py
|
|
||||||
- name: Login to Container Registry
|
- name: Login to Container Registry
|
||||||
uses: docker/login-action@v1
|
uses: docker/login-action@v2
|
||||||
if: ${{ steps.ev.outputs.shouldBuild == 'true' }}
|
if: ${{ steps.ev.outputs.shouldBuild == 'true' }}
|
||||||
with:
|
with:
|
||||||
registry: ghcr.io
|
registry: ghcr.io
|
||||||
username: ${{ github.repository_owner }}
|
username: ${{ github.repository_owner }}
|
||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
- name: Generate API
|
||||||
|
run: make gen-client-go
|
||||||
- name: Building Docker Image
|
- name: Building Docker Image
|
||||||
uses: docker/build-push-action@v2
|
uses: docker/build-push-action@v3
|
||||||
with:
|
with:
|
||||||
push: ${{ steps.ev.outputs.shouldBuild == 'true' }}
|
push: ${{ steps.ev.outputs.shouldBuild == 'true' }}
|
||||||
tags: |
|
tags: |
|
||||||
@ -95,6 +91,7 @@ jobs:
|
|||||||
file: ${{ matrix.type }}.Dockerfile
|
file: ${{ matrix.type }}.Dockerfile
|
||||||
build-args: |
|
build-args: |
|
||||||
GIT_BUILD_HASH=${{ steps.ev.outputs.sha }}
|
GIT_BUILD_HASH=${{ steps.ev.outputs.sha }}
|
||||||
|
VERSION_FAMILY=${{ steps.ev.outputs.versionFamily }}
|
||||||
platforms: ${{ matrix.arch }}
|
platforms: ${{ matrix.arch }}
|
||||||
build-outpost-binary:
|
build-outpost-binary:
|
||||||
timeout-minutes: 120
|
timeout-minutes: 120
|
||||||
@ -111,18 +108,20 @@ jobs:
|
|||||||
goarch: [amd64, arm64]
|
goarch: [amd64, arm64]
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-go@v2
|
- uses: actions/setup-go@v3
|
||||||
with:
|
with:
|
||||||
go-version: "^1.17"
|
go-version: "^1.17"
|
||||||
- uses: actions/setup-node@v3.0.0
|
- uses: actions/setup-node@v3.4.1
|
||||||
with:
|
with:
|
||||||
node-version: '16'
|
node-version: '16'
|
||||||
cache: 'npm'
|
cache: 'npm'
|
||||||
cache-dependency-path: web/package-lock.json
|
cache-dependency-path: web/package-lock.json
|
||||||
|
- name: Generate API
|
||||||
|
run: make gen-client-go
|
||||||
- name: Build web
|
- name: Build web
|
||||||
|
working-directory: web/
|
||||||
run: |
|
run: |
|
||||||
cd web
|
npm ci
|
||||||
npm install
|
|
||||||
npm run build-proxy
|
npm run build-proxy
|
||||||
- name: Build outpost
|
- name: Build outpost
|
||||||
run: |
|
run: |
|
||||||
@ -130,7 +129,7 @@ jobs:
|
|||||||
export GOOS=${{ matrix.goos }}
|
export GOOS=${{ matrix.goos }}
|
||||||
export GOARCH=${{ matrix.goarch }}
|
export GOARCH=${{ matrix.goarch }}
|
||||||
go build -tags=outpost_static_embed -v -o ./authentik-outpost-${{ matrix.type }}_${{ matrix.goos }}_${{ matrix.goarch }} ./cmd/${{ matrix.type }}
|
go build -tags=outpost_static_embed -v -o ./authentik-outpost-${{ matrix.type }}_${{ matrix.goos }}_${{ matrix.goarch }} ./cmd/${{ matrix.type }}
|
||||||
- uses: actions/upload-artifact@v2
|
- uses: actions/upload-artifact@v3
|
||||||
with:
|
with:
|
||||||
name: authentik-outpost-${{ matrix.type }}_${{ matrix.goos }}_${{ matrix.goarch }}
|
name: authentik-outpost-${{ matrix.type }}_${{ matrix.goos }}_${{ matrix.goarch }}
|
||||||
path: ./authentik-outpost-${{ matrix.type }}_${{ matrix.goos }}_${{ matrix.goarch }}
|
path: ./authentik-outpost-${{ matrix.type }}_${{ matrix.goos }}_${{ matrix.goarch }}
|
||||||
|
67
.github/workflows/ci-web.yml
vendored
67
.github/workflows/ci-web.yml
vendored
@ -3,68 +3,67 @@ name: authentik-ci-web
|
|||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- master
|
- main
|
||||||
- next
|
- next
|
||||||
- version-*
|
- version-*
|
||||||
pull_request:
|
pull_request:
|
||||||
branches:
|
branches:
|
||||||
- master
|
- main
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
lint-eslint:
|
lint-eslint:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-node@v3.0.0
|
- uses: actions/setup-node@v3.4.1
|
||||||
with:
|
with:
|
||||||
node-version: '16'
|
node-version: '16'
|
||||||
cache: 'npm'
|
cache: 'npm'
|
||||||
cache-dependency-path: web/package-lock.json
|
cache-dependency-path: web/package-lock.json
|
||||||
- run: |
|
- working-directory: web/
|
||||||
cd web
|
run: npm ci
|
||||||
npm install
|
|
||||||
- name: Generate API
|
- name: Generate API
|
||||||
run: make gen-web
|
run: make gen-client-ts
|
||||||
- name: Eslint
|
- name: Eslint
|
||||||
run: |
|
working-directory: web/
|
||||||
cd web
|
run: npm run lint
|
||||||
npm run lint
|
|
||||||
lint-prettier:
|
lint-prettier:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-node@v3.0.0
|
- uses: actions/setup-node@v3.4.1
|
||||||
with:
|
with:
|
||||||
node-version: '16'
|
node-version: '16'
|
||||||
cache: 'npm'
|
cache: 'npm'
|
||||||
cache-dependency-path: web/package-lock.json
|
cache-dependency-path: web/package-lock.json
|
||||||
- run: |
|
- working-directory: web/
|
||||||
cd web
|
run: npm ci
|
||||||
npm install
|
|
||||||
- name: Generate API
|
- name: Generate API
|
||||||
run: make gen-web
|
run: make gen-client-ts
|
||||||
- name: prettier
|
- name: prettier
|
||||||
run: |
|
working-directory: web/
|
||||||
cd web
|
run: npm run prettier-check
|
||||||
npm run prettier-check
|
|
||||||
lint-lit-analyse:
|
lint-lit-analyse:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-node@v3.0.0
|
- uses: actions/setup-node@v3.4.1
|
||||||
with:
|
with:
|
||||||
node-version: '16'
|
node-version: '16'
|
||||||
cache: 'npm'
|
cache: 'npm'
|
||||||
cache-dependency-path: web/package-lock.json
|
cache-dependency-path: web/package-lock.json
|
||||||
- run: |
|
- working-directory: web/
|
||||||
cd web
|
|
||||||
npm install
|
|
||||||
- name: Generate API
|
|
||||||
run: make gen-web
|
|
||||||
- name: lit-analyse
|
|
||||||
run: |
|
run: |
|
||||||
cd web
|
npm ci
|
||||||
npm run lit-analyse
|
# lit-analyse doesn't understand path rewrites, so make it
|
||||||
|
# belive it's an actual module
|
||||||
|
cd node_modules/@goauthentik
|
||||||
|
ln -s ../../src/ web
|
||||||
|
- name: Generate API
|
||||||
|
run: make gen-client-ts
|
||||||
|
- name: lit-analyse
|
||||||
|
working-directory: web/
|
||||||
|
run: npm run lit-analyse
|
||||||
ci-web-mark:
|
ci-web-mark:
|
||||||
needs:
|
needs:
|
||||||
- lint-eslint
|
- lint-eslint
|
||||||
@ -79,17 +78,15 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-node@v3.0.0
|
- uses: actions/setup-node@v3.4.1
|
||||||
with:
|
with:
|
||||||
node-version: '16'
|
node-version: '16'
|
||||||
cache: 'npm'
|
cache: 'npm'
|
||||||
cache-dependency-path: web/package-lock.json
|
cache-dependency-path: web/package-lock.json
|
||||||
- run: |
|
- working-directory: web/
|
||||||
cd web
|
run: npm ci
|
||||||
npm install
|
|
||||||
- name: Generate API
|
- name: Generate API
|
||||||
run: make gen-web
|
run: make gen-client-ts
|
||||||
- name: build
|
- name: build
|
||||||
run: |
|
working-directory: web/
|
||||||
cd web
|
run: npm run build
|
||||||
npm run build
|
|
||||||
|
33
.github/workflows/ci-website.yml
vendored
Normal file
33
.github/workflows/ci-website.yml
vendored
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
name: authentik-ci-website
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
- next
|
||||||
|
- version-*
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
lint-prettier:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- uses: actions/setup-node@v3.4.1
|
||||||
|
with:
|
||||||
|
node-version: '16'
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: website/package-lock.json
|
||||||
|
- working-directory: website/
|
||||||
|
run: npm ci
|
||||||
|
- name: prettier
|
||||||
|
working-directory: website/
|
||||||
|
run: npm run prettier-check
|
||||||
|
ci-website-mark:
|
||||||
|
needs:
|
||||||
|
- lint-prettier
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- run: echo mark
|
10
.github/workflows/codeql-analysis.yml
vendored
10
.github/workflows/codeql-analysis.yml
vendored
@ -2,10 +2,10 @@ name: "CodeQL"
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [ master, '*', next, version* ]
|
branches: [ main, '*', next, version* ]
|
||||||
pull_request:
|
pull_request:
|
||||||
# The branches below must be a subset of the branches above
|
# The branches below must be a subset of the branches above
|
||||||
branches: [ master ]
|
branches: [ main ]
|
||||||
schedule:
|
schedule:
|
||||||
- cron: '30 6 * * 5'
|
- cron: '30 6 * * 5'
|
||||||
|
|
||||||
@ -32,7 +32,7 @@ jobs:
|
|||||||
|
|
||||||
# Initializes the CodeQL tools for scanning.
|
# Initializes the CodeQL tools for scanning.
|
||||||
- name: Initialize CodeQL
|
- name: Initialize CodeQL
|
||||||
uses: github/codeql-action/init@v1
|
uses: github/codeql-action/init@v2
|
||||||
with:
|
with:
|
||||||
languages: ${{ matrix.language }}
|
languages: ${{ matrix.language }}
|
||||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||||
@ -43,7 +43,7 @@ jobs:
|
|||||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||||
# If this step fails, then you should remove it and run the build manually (see below)
|
# If this step fails, then you should remove it and run the build manually (see below)
|
||||||
- name: Autobuild
|
- name: Autobuild
|
||||||
uses: github/codeql-action/autobuild@v1
|
uses: github/codeql-action/autobuild@v2
|
||||||
|
|
||||||
# ℹ️ Command-line programs to run using the OS shell.
|
# ℹ️ Command-line programs to run using the OS shell.
|
||||||
# 📚 https://git.io/JvXDl
|
# 📚 https://git.io/JvXDl
|
||||||
@ -57,4 +57,4 @@ jobs:
|
|||||||
# make release
|
# make release
|
||||||
|
|
||||||
- name: Perform CodeQL Analysis
|
- name: Perform CodeQL Analysis
|
||||||
uses: github/codeql-action/analyze@v1
|
uses: github/codeql-action/analyze@v2
|
||||||
|
2
.github/workflows/ghcr-retention.yml
vendored
2
.github/workflows/ghcr-retention.yml
vendored
@ -19,4 +19,4 @@ jobs:
|
|||||||
org-name: goauthentik
|
org-name: goauthentik
|
||||||
untagged-only: false
|
untagged-only: false
|
||||||
token: ${{ secrets.GHCR_CLEANUP_TOKEN }}
|
token: ${{ secrets.GHCR_CLEANUP_TOKEN }}
|
||||||
skip-tags: gh-next,gh-master
|
skip-tags: gh-next,gh-main
|
||||||
|
57
.github/workflows/release-publish.yml
vendored
57
.github/workflows/release-publish.yml
vendored
@ -5,34 +5,38 @@ on:
|
|||||||
types: [published, created]
|
types: [published, created]
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
# Build
|
|
||||||
build-server:
|
build-server:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@v1.2.0
|
uses: docker/setup-qemu-action@v2.0.0
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v1
|
uses: docker/setup-buildx-action@v2
|
||||||
|
- name: prepare variables
|
||||||
|
uses: ./.github/actions/docker-push-variables
|
||||||
|
id: ev
|
||||||
- name: Docker Login Registry
|
- name: Docker Login Registry
|
||||||
uses: docker/login-action@v1
|
uses: docker/login-action@v2
|
||||||
with:
|
with:
|
||||||
username: ${{ secrets.DOCKER_USERNAME }}
|
username: ${{ secrets.DOCKER_USERNAME }}
|
||||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
- name: Login to GitHub Container Registry
|
- name: Login to GitHub Container Registry
|
||||||
uses: docker/login-action@v1
|
uses: docker/login-action@v2
|
||||||
with:
|
with:
|
||||||
registry: ghcr.io
|
registry: ghcr.io
|
||||||
username: ${{ github.repository_owner }}
|
username: ${{ github.repository_owner }}
|
||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
- name: Building Docker Image
|
- name: Building Docker Image
|
||||||
uses: docker/build-push-action@v2
|
uses: docker/build-push-action@v3
|
||||||
with:
|
with:
|
||||||
push: ${{ github.event_name == 'release' }}
|
push: ${{ github.event_name == 'release' }}
|
||||||
tags: |
|
tags: |
|
||||||
beryju/authentik:2022.3.2,
|
beryju/authentik:${{ steps.ev.outputs.version }},
|
||||||
|
beryju/authentik:${{ steps.ev.outputs.versionFamily }},
|
||||||
beryju/authentik:latest,
|
beryju/authentik:latest,
|
||||||
ghcr.io/goauthentik/server:2022.3.2,
|
ghcr.io/goauthentik/server:${{ steps.ev.outputs.version }},
|
||||||
|
ghcr.io/goauthentik/server:${{ steps.ev.outputs.versionFamily }},
|
||||||
ghcr.io/goauthentik/server:latest
|
ghcr.io/goauthentik/server:latest
|
||||||
platforms: linux/amd64,linux/arm64
|
platforms: linux/amd64,linux/arm64
|
||||||
context: .
|
context: .
|
||||||
@ -46,32 +50,37 @@ jobs:
|
|||||||
- ldap
|
- ldap
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-go@v2
|
- uses: actions/setup-go@v3
|
||||||
with:
|
with:
|
||||||
go-version: "^1.17"
|
go-version: "^1.17"
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@v1.2.0
|
uses: docker/setup-qemu-action@v2.0.0
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v1
|
uses: docker/setup-buildx-action@v2
|
||||||
|
- name: prepare variables
|
||||||
|
uses: ./.github/actions/docker-push-variables
|
||||||
|
id: ev
|
||||||
- name: Docker Login Registry
|
- name: Docker Login Registry
|
||||||
uses: docker/login-action@v1
|
uses: docker/login-action@v2
|
||||||
with:
|
with:
|
||||||
username: ${{ secrets.DOCKER_USERNAME }}
|
username: ${{ secrets.DOCKER_USERNAME }}
|
||||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
- name: Login to GitHub Container Registry
|
- name: Login to GitHub Container Registry
|
||||||
uses: docker/login-action@v1
|
uses: docker/login-action@v2
|
||||||
with:
|
with:
|
||||||
registry: ghcr.io
|
registry: ghcr.io
|
||||||
username: ${{ github.repository_owner }}
|
username: ${{ github.repository_owner }}
|
||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
- name: Building Docker Image
|
- name: Building Docker Image
|
||||||
uses: docker/build-push-action@v2
|
uses: docker/build-push-action@v3
|
||||||
with:
|
with:
|
||||||
push: ${{ github.event_name == 'release' }}
|
push: ${{ github.event_name == 'release' }}
|
||||||
tags: |
|
tags: |
|
||||||
beryju/authentik-${{ matrix.type }}:2022.3.2,
|
beryju/authentik-${{ matrix.type }}:${{ steps.ev.outputs.version }},
|
||||||
|
beryju/authentik-${{ matrix.type }}:${{ steps.ev.outputs.versionFamily }},
|
||||||
beryju/authentik-${{ matrix.type }}:latest,
|
beryju/authentik-${{ matrix.type }}:latest,
|
||||||
ghcr.io/goauthentik/${{ matrix.type }}:2022.3.2,
|
ghcr.io/goauthentik/${{ matrix.type }}:${{ steps.ev.outputs.version }},
|
||||||
|
ghcr.io/goauthentik/${{ matrix.type }}:${{ steps.ev.outputs.versionFamily }},
|
||||||
ghcr.io/goauthentik/${{ matrix.type }}:latest
|
ghcr.io/goauthentik/${{ matrix.type }}:latest
|
||||||
file: ${{ matrix.type }}.Dockerfile
|
file: ${{ matrix.type }}.Dockerfile
|
||||||
platforms: linux/amd64,linux/arm64
|
platforms: linux/amd64,linux/arm64
|
||||||
@ -88,18 +97,18 @@ jobs:
|
|||||||
goarch: [amd64, arm64]
|
goarch: [amd64, arm64]
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-go@v2
|
- uses: actions/setup-go@v3
|
||||||
with:
|
with:
|
||||||
go-version: "^1.17"
|
go-version: "^1.17"
|
||||||
- uses: actions/setup-node@v3.0.0
|
- uses: actions/setup-node@v3.4.1
|
||||||
with:
|
with:
|
||||||
node-version: '16'
|
node-version: '16'
|
||||||
cache: 'npm'
|
cache: 'npm'
|
||||||
cache-dependency-path: web/package-lock.json
|
cache-dependency-path: web/package-lock.json
|
||||||
- name: Build web
|
- name: Build web
|
||||||
|
working-directory: web/
|
||||||
run: |
|
run: |
|
||||||
cd web
|
npm ci
|
||||||
npm install
|
|
||||||
npm run build-proxy
|
npm run build-proxy
|
||||||
- name: Build outpost
|
- name: Build outpost
|
||||||
run: |
|
run: |
|
||||||
@ -129,7 +138,7 @@ jobs:
|
|||||||
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
|
docker-compose run -u root server test-all
|
||||||
sentry-release:
|
sentry-release:
|
||||||
needs:
|
needs:
|
||||||
- build-server
|
- build-server
|
||||||
@ -138,6 +147,9 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
|
- name: prepare variables
|
||||||
|
uses: ./.github/actions/docker-push-variables
|
||||||
|
id: ev
|
||||||
- name: Get static files from docker image
|
- name: Get static files from docker image
|
||||||
run: |
|
run: |
|
||||||
docker pull ghcr.io/goauthentik/server:latest
|
docker pull ghcr.io/goauthentik/server:latest
|
||||||
@ -145,6 +157,7 @@ jobs:
|
|||||||
docker cp ${container}:web/ .
|
docker cp ${container}:web/ .
|
||||||
- name: Create a Sentry.io release
|
- name: Create a Sentry.io release
|
||||||
uses: getsentry/action-release@v1
|
uses: getsentry/action-release@v1
|
||||||
|
continue-on-error: true
|
||||||
if: ${{ github.event_name == 'release' }}
|
if: ${{ github.event_name == 'release' }}
|
||||||
env:
|
env:
|
||||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||||
@ -152,7 +165,7 @@ jobs:
|
|||||||
SENTRY_PROJECT: authentik
|
SENTRY_PROJECT: authentik
|
||||||
SENTRY_URL: https://sentry.beryju.org
|
SENTRY_URL: https://sentry.beryju.org
|
||||||
with:
|
with:
|
||||||
version: authentik@2022.3.2
|
version: authentik@${{ steps.ev.outputs.version }}
|
||||||
environment: beryjuorg-prod
|
environment: beryjuorg-prod
|
||||||
sourcemaps: './web/dist'
|
sourcemaps: './web/dist'
|
||||||
url_prefix: '~/static/dist'
|
url_prefix: '~/static/dist'
|
||||||
|
7
.github/workflows/release-tag.yml
vendored
7
.github/workflows/release-tag.yml
vendored
@ -16,15 +16,12 @@ jobs:
|
|||||||
echo "PG_PASS=$(openssl rand -base64 32)" >> .env
|
echo "PG_PASS=$(openssl rand -base64 32)" >> .env
|
||||||
echo "AUTHENTIK_SECRET_KEY=$(openssl rand -base64 32)" >> .env
|
echo "AUTHENTIK_SECRET_KEY=$(openssl rand -base64 32)" >> .env
|
||||||
docker buildx install
|
docker buildx install
|
||||||
docker build \
|
docker build -t testing:latest .
|
||||||
--no-cache \
|
|
||||||
-t testing:latest \
|
|
||||||
-f Dockerfile .
|
|
||||||
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
|
docker-compose run -u root server test-all
|
||||||
- name: Extract version number
|
- name: Extract version number
|
||||||
id: get_version
|
id: get_version
|
||||||
uses: actions/github-script@v6
|
uses: actions/github-script@v6
|
||||||
|
28
.github/workflows/translation-compile.yml
vendored
28
.github/workflows/translation-compile.yml
vendored
@ -1,14 +1,12 @@
|
|||||||
name: authentik-backend-translate-compile
|
name: authentik-backend-translate-compile
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [ master ]
|
branches: [ main ]
|
||||||
paths:
|
paths:
|
||||||
- '/locale/'
|
- '/locale/'
|
||||||
pull_request:
|
pull_request:
|
||||||
paths:
|
paths:
|
||||||
- '/locale/'
|
- '/locale/'
|
||||||
schedule:
|
|
||||||
- cron: "0 */2 * * *"
|
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
env:
|
env:
|
||||||
@ -21,23 +19,12 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-python@v3
|
- name: Setup authentik env
|
||||||
- id: cache-poetry
|
uses: ./.github/actions/setup
|
||||||
uses: actions/cache@v2.1.7
|
|
||||||
with:
|
|
||||||
path: ~/.cache/pypoetry/virtualenvs
|
|
||||||
key: ${{ runner.os }}-poetry-cache-v2-${{ hashFiles('**/poetry.lock') }}
|
|
||||||
- name: prepare
|
|
||||||
env:
|
|
||||||
INSTALL: ${{ steps.cache-poetry.outputs.cache-hit }}
|
|
||||||
run: |
|
|
||||||
sudo apt-get update
|
|
||||||
sudo apt-get install -y gettext
|
|
||||||
scripts/ci_prepare.sh
|
|
||||||
- name: run compile
|
- name: run compile
|
||||||
run: poetry run ./manage.py compilemessages
|
run: poetry run ./manage.py compilemessages
|
||||||
- name: Create Pull Request
|
- name: Create Pull Request
|
||||||
uses: peter-evans/create-pull-request@v3
|
uses: peter-evans/create-pull-request@v4
|
||||||
id: cpr
|
id: cpr
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.GITHUB_TOKEN }}
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
@ -47,10 +34,3 @@ jobs:
|
|||||||
body: "core: compile backend translations"
|
body: "core: compile backend translations"
|
||||||
delete-branch: true
|
delete-branch: true
|
||||||
signoff: true
|
signoff: true
|
||||||
- name: Enable Pull Request Automerge
|
|
||||||
if: steps.cpr.outputs.pull-request-operation == 'created'
|
|
||||||
uses: peter-evans/enable-pull-request-automerge@v1
|
|
||||||
with:
|
|
||||||
token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
pull-request-number: ${{ steps.cpr.outputs.pull-request-number }}
|
|
||||||
merge-method: squash
|
|
||||||
|
30
.github/workflows/web-api-publish.yml
vendored
30
.github/workflows/web-api-publish.yml
vendored
@ -1,48 +1,42 @@
|
|||||||
name: authentik-web-api-publish
|
name: authentik-web-api-publish
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [ master ]
|
branches: [ main ]
|
||||||
paths:
|
paths:
|
||||||
- 'schema.yml'
|
- 'schema.yml'
|
||||||
|
workflow_dispatch:
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
# Setup .npmrc file to publish to npm
|
# Setup .npmrc file to publish to npm
|
||||||
- uses: actions/setup-node@v3.0.0
|
- uses: actions/setup-node@v3.4.1
|
||||||
with:
|
with:
|
||||||
node-version: '16'
|
node-version: '16'
|
||||||
registry-url: 'https://registry.npmjs.org'
|
registry-url: 'https://registry.npmjs.org'
|
||||||
- name: Generate API Client
|
- name: Generate API Client
|
||||||
run: make gen-web
|
run: make gen-client-ts
|
||||||
- name: Publish package
|
- name: Publish package
|
||||||
|
working-directory: gen-ts-api/
|
||||||
run: |
|
run: |
|
||||||
cd web-api/
|
npm ci
|
||||||
npm i
|
|
||||||
npm publish
|
npm publish
|
||||||
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/
|
||||||
run: |
|
run: |
|
||||||
cd web/
|
export VERSION=`node -e 'console.log(require("../gen-ts-api/package.json").version)'`
|
||||||
export VERSION=`node -e 'console.log(require("../web-api/package.json").version)'`
|
|
||||||
npm i @goauthentik/api@$VERSION
|
npm i @goauthentik/api@$VERSION
|
||||||
- name: Create Pull Request
|
- name: Create Pull Request
|
||||||
uses: peter-evans/create-pull-request@v3
|
uses: peter-evans/create-pull-request@v4
|
||||||
id: cpr
|
id: cpr
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.GITHUB_TOKEN }}
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
branch: update-web-api-client
|
branch: update-web-api-client
|
||||||
commit-message: "web: Update Web API Client version"
|
commit-message: "web: bump API Client version"
|
||||||
title: "web: Update Web API Client version"
|
title: "web: bump API Client version"
|
||||||
body: "web: Update Web API Client version"
|
body: "web: bump API Client version"
|
||||||
delete-branch: true
|
delete-branch: true
|
||||||
signoff: true
|
signoff: true
|
||||||
- name: Enable Pull Request Automerge
|
|
||||||
if: steps.cpr.outputs.pull-request-operation == 'created'
|
|
||||||
uses: peter-evans/enable-pull-request-automerge@v1
|
|
||||||
with:
|
|
||||||
token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
pull-request-number: ${{ steps.cpr.outputs.pull-request-number }}
|
|
||||||
merge-method: squash
|
|
||||||
|
4
.gitignore
vendored
4
.gitignore
vendored
@ -193,7 +193,6 @@ pip-selfcheck.json
|
|||||||
# End of https://www.gitignore.io/api/python,django
|
# End of https://www.gitignore.io/api/python,django
|
||||||
/static/
|
/static/
|
||||||
local.env.yml
|
local.env.yml
|
||||||
.vscode/
|
|
||||||
|
|
||||||
# Selenium Screenshots
|
# Selenium Screenshots
|
||||||
selenium_screenshots/
|
selenium_screenshots/
|
||||||
@ -202,5 +201,4 @@ media/
|
|||||||
*mmdb
|
*mmdb
|
||||||
|
|
||||||
.idea/
|
.idea/
|
||||||
/api/
|
/gen-*/
|
||||||
/web-api/
|
|
||||||
|
13
.vscode/settings.json
vendored
13
.vscode/settings.json
vendored
@ -1,5 +1,6 @@
|
|||||||
{
|
{
|
||||||
"cSpell.words": [
|
"cSpell.words": [
|
||||||
|
"akadmin",
|
||||||
"asgi",
|
"asgi",
|
||||||
"authentik",
|
"authentik",
|
||||||
"authn",
|
"authn",
|
||||||
@ -19,7 +20,15 @@
|
|||||||
"todo-tree.tree.showCountsInTree": true,
|
"todo-tree.tree.showCountsInTree": true,
|
||||||
"todo-tree.tree.showBadges": true,
|
"todo-tree.tree.showBadges": true,
|
||||||
"python.formatting.provider": "black",
|
"python.formatting.provider": "black",
|
||||||
"files.associations": {
|
"yaml.customTags": [
|
||||||
"*.akflow": "json"
|
"!Find sequence",
|
||||||
|
"!KeyOf scalar"
|
||||||
|
],
|
||||||
|
"typescript.preferences.importModuleSpecifier": "non-relative",
|
||||||
|
"typescript.preferences.importModuleSpecifierEnding": "index",
|
||||||
|
"typescript.tsdk": "./web/node_modules/typescript/lib",
|
||||||
|
"typescript.enablePromptUseWorkspaceTsdk": true,
|
||||||
|
"yaml.schemas": {
|
||||||
|
"./blueprints/schema.json": "blueprints/**/*.yaml"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
86
.vscode/tasks.json
vendored
Normal file
86
.vscode/tasks.json
vendored
Normal file
@ -0,0 +1,86 @@
|
|||||||
|
{
|
||||||
|
"version": "2.0.0",
|
||||||
|
"tasks": [
|
||||||
|
{
|
||||||
|
"label": "authentik[core]: format & test",
|
||||||
|
"command": "poetry",
|
||||||
|
"args": [
|
||||||
|
"run",
|
||||||
|
"make"
|
||||||
|
],
|
||||||
|
"group": "build",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "authentik[core]: run",
|
||||||
|
"command": "poetry",
|
||||||
|
"args": [
|
||||||
|
"run",
|
||||||
|
"make",
|
||||||
|
"run",
|
||||||
|
],
|
||||||
|
"group": "build",
|
||||||
|
"presentation": {
|
||||||
|
"panel": "dedicated",
|
||||||
|
"group": "running"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "authentik[web]: format",
|
||||||
|
"command": "make",
|
||||||
|
"args": ["web"],
|
||||||
|
"group": "build",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "authentik[web]: watch",
|
||||||
|
"command": "make",
|
||||||
|
"args": ["web-watch"],
|
||||||
|
"group": "build",
|
||||||
|
"presentation": {
|
||||||
|
"panel": "dedicated",
|
||||||
|
"group": "running"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "authentik: install",
|
||||||
|
"command": "make",
|
||||||
|
"args": ["install"],
|
||||||
|
"group": "build",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "authentik: i18n-extract",
|
||||||
|
"command": "poetry",
|
||||||
|
"args": [
|
||||||
|
"run",
|
||||||
|
"make",
|
||||||
|
"i18n-extract"
|
||||||
|
],
|
||||||
|
"group": "build",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "authentik[website]: format",
|
||||||
|
"command": "make",
|
||||||
|
"args": ["website"],
|
||||||
|
"group": "build",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "authentik[website]: watch",
|
||||||
|
"command": "make",
|
||||||
|
"args": ["website-watch"],
|
||||||
|
"group": "build",
|
||||||
|
"presentation": {
|
||||||
|
"panel": "dedicated",
|
||||||
|
"group": "running"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "authentik[api]: generate",
|
||||||
|
"command": "poetry",
|
||||||
|
"args": [
|
||||||
|
"run",
|
||||||
|
"make",
|
||||||
|
"gen"
|
||||||
|
],
|
||||||
|
"group": "build"
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
@ -60,7 +60,7 @@ representative at an online or offline event.
|
|||||||
|
|
||||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||||
reported to the community leaders responsible for enforcement at
|
reported to the community leaders responsible for enforcement at
|
||||||
hello@beryju.org.
|
hello@goauthentik.io.
|
||||||
All complaints will be reviewed and investigated promptly and fairly.
|
All complaints will be reviewed and investigated promptly and fairly.
|
||||||
|
|
||||||
All community leaders are obligated to respect the privacy and security of the
|
All community leaders are obligated to respect the privacy and security of the
|
||||||
|
60
Dockerfile
60
Dockerfile
@ -1,22 +1,36 @@
|
|||||||
# Stage 1: Build website
|
# Stage 1: Build website
|
||||||
FROM --platform=${BUILDPLATFORM} docker.io/node:16 as website-builder
|
FROM --platform=${BUILDPLATFORM} docker.io/node:18 as website-builder
|
||||||
|
|
||||||
COPY ./website /work/website/
|
COPY ./website /work/website/
|
||||||
|
COPY ./blueprints /work/blueprints/
|
||||||
|
|
||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
RUN cd /work/website && npm i && npm run build-docs-only
|
WORKDIR /work/website
|
||||||
|
RUN npm ci && npm run build-docs-only
|
||||||
|
|
||||||
# Stage 2: Build webui
|
# Stage 2: Build webui
|
||||||
FROM --platform=${BUILDPLATFORM} docker.io/node:16 as web-builder
|
FROM --platform=${BUILDPLATFORM} docker.io/node:18 as web-builder
|
||||||
|
|
||||||
COPY ./web /work/web/
|
COPY ./web /work/web/
|
||||||
COPY ./website /work/website/
|
COPY ./website /work/website/
|
||||||
|
|
||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
RUN cd /work/web && npm i && npm run build
|
WORKDIR /work/web
|
||||||
|
RUN npm ci && npm run build
|
||||||
|
|
||||||
# Stage 3: Build go proxy
|
# Stage 3: Poetry to requirements.txt export
|
||||||
FROM docker.io/golang:1.17.8-bullseye AS builder
|
FROM docker.io/python:3.10.6-slim-bullseye AS poetry-locker
|
||||||
|
|
||||||
|
WORKDIR /work
|
||||||
|
COPY ./pyproject.toml /work
|
||||||
|
COPY ./poetry.lock /work
|
||||||
|
|
||||||
|
RUN pip install --no-cache-dir poetry && \
|
||||||
|
poetry export -f requirements.txt --output requirements.txt && \
|
||||||
|
poetry export -f requirements.txt --dev --output requirements-dev.txt
|
||||||
|
|
||||||
|
# Stage 4: Build go proxy
|
||||||
|
FROM docker.io/golang:1.19.0-bullseye AS go-builder
|
||||||
|
|
||||||
WORKDIR /work
|
WORKDIR /work
|
||||||
|
|
||||||
@ -31,8 +45,8 @@ COPY ./go.sum /work/go.sum
|
|||||||
|
|
||||||
RUN go build -o /work/authentik ./cmd/server/main.go
|
RUN go build -o /work/authentik ./cmd/server/main.go
|
||||||
|
|
||||||
# Stage 4: Run
|
# Stage 5: Run
|
||||||
FROM docker.io/python:3.10.2-slim-bullseye
|
FROM docker.io/python:3.10.6-slim-bullseye AS final-image
|
||||||
|
|
||||||
LABEL org.opencontainers.image.url https://goauthentik.io
|
LABEL org.opencontainers.image.url https://goauthentik.io
|
||||||
LABEL org.opencontainers.image.description goauthentik.io Main server image, see https://goauthentik.io for more info.
|
LABEL org.opencontainers.image.description goauthentik.io Main server image, see https://goauthentik.io for more info.
|
||||||
@ -43,24 +57,23 @@ WORKDIR /
|
|||||||
ARG GIT_BUILD_HASH
|
ARG GIT_BUILD_HASH
|
||||||
ENV GIT_BUILD_HASH=$GIT_BUILD_HASH
|
ENV GIT_BUILD_HASH=$GIT_BUILD_HASH
|
||||||
|
|
||||||
COPY ./pyproject.toml /
|
COPY --from=poetry-locker /work/requirements.txt /
|
||||||
COPY ./poetry.lock /
|
COPY --from=poetry-locker /work/requirements-dev.txt /
|
||||||
|
|
||||||
RUN apt-get update && \
|
RUN apt-get update && \
|
||||||
apt-get install -y --no-install-recommends \
|
# Required for installing pip packages
|
||||||
curl ca-certificates gnupg git runit libpq-dev \
|
apt-get install -y --no-install-recommends build-essential pkg-config libxmlsec1-dev && \
|
||||||
postgresql-client build-essential libxmlsec1-dev \
|
# Required for runtime
|
||||||
pkg-config libmaxminddb0 && \
|
apt-get install -y --no-install-recommends libxmlsec1-openssl libmaxminddb0 && \
|
||||||
pip install poetry && \
|
# Required for bootstrap & healtcheck
|
||||||
poetry config virtualenvs.create false && \
|
apt-get install -y --no-install-recommends curl runit && \
|
||||||
poetry install --no-dev && \
|
pip install --no-cache-dir -r /requirements.txt && \
|
||||||
rm -rf ~/.cache/pypoetry && \
|
apt-get remove --purge -y build-essential pkg-config libxmlsec1-dev && \
|
||||||
apt-get remove --purge -y build-essential git && \
|
|
||||||
apt-get autoremove --purge -y && \
|
apt-get autoremove --purge -y && \
|
||||||
apt-get clean && \
|
apt-get clean && \
|
||||||
rm -rf /tmp/* /var/lib/apt/lists/* /var/tmp/ && \
|
rm -rf /tmp/* /var/lib/apt/lists/* /var/tmp/ && \
|
||||||
adduser --system --no-create-home --uid 1000 --group --home /authentik authentik && \
|
adduser --system --no-create-home --uid 1000 --group --home /authentik authentik && \
|
||||||
mkdir -p /certs /media && \
|
mkdir -p /certs /media /blueprints && \
|
||||||
mkdir -p /authentik/.ssh && \
|
mkdir -p /authentik/.ssh && \
|
||||||
chown authentik:authentik /certs /media /authentik/.ssh
|
chown authentik:authentik /certs /media /authentik/.ssh
|
||||||
|
|
||||||
@ -69,13 +82,14 @@ COPY ./pyproject.toml /
|
|||||||
COPY ./xml /xml
|
COPY ./xml /xml
|
||||||
COPY ./tests /tests
|
COPY ./tests /tests
|
||||||
COPY ./manage.py /
|
COPY ./manage.py /
|
||||||
|
COPY ./blueprints /blueprints
|
||||||
COPY ./lifecycle/ /lifecycle
|
COPY ./lifecycle/ /lifecycle
|
||||||
COPY --from=builder /work/authentik /authentik-proxy
|
COPY --from=go-builder /work/authentik /authentik-proxy
|
||||||
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/help/ /website/help/
|
||||||
|
|
||||||
USER authentik
|
USER 1000
|
||||||
|
|
||||||
ENV TMPDIR /dev/shm/
|
ENV TMPDIR /dev/shm/
|
||||||
ENV PYTHONUNBUFFERED 1
|
ENV PYTHONUNBUFFERED 1
|
||||||
@ -83,4 +97,4 @@ ENV PATH "/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin
|
|||||||
|
|
||||||
HEALTHCHECK --interval=30s --timeout=30s --start-period=60s --retries=3 CMD [ "/lifecycle/ak", "healthcheck" ]
|
HEALTHCHECK --interval=30s --timeout=30s --start-period=60s --retries=3 CMD [ "/lifecycle/ak", "healthcheck" ]
|
||||||
|
|
||||||
ENTRYPOINT [ "/lifecycle/ak" ]
|
ENTRYPOINT [ "/usr/local/bin/dumb-init", "--", "/lifecycle/ak" ]
|
||||||
|
174
Makefile
174
Makefile
@ -18,14 +18,23 @@ test-e2e-rest:
|
|||||||
test-go:
|
test-go:
|
||||||
go test -timeout 0 -v -race -cover ./...
|
go test -timeout 0 -v -race -cover ./...
|
||||||
|
|
||||||
|
test-docker:
|
||||||
|
echo "PG_PASS=$(openssl rand -base64 32)" >> .env
|
||||||
|
echo "AUTHENTIK_SECRET_KEY=$(openssl rand -base64 32)" >> .env
|
||||||
|
docker-compose pull -q
|
||||||
|
docker-compose up --no-start
|
||||||
|
docker-compose start postgresql redis
|
||||||
|
docker-compose run -u root server test
|
||||||
|
rm -f .env
|
||||||
|
|
||||||
test:
|
test:
|
||||||
coverage run manage.py test authentik
|
coverage run manage.py test authentik
|
||||||
coverage html
|
coverage html
|
||||||
coverage report
|
coverage report
|
||||||
|
|
||||||
lint-fix:
|
lint-fix:
|
||||||
isort authentik tests lifecycle
|
isort authentik tests scripts lifecycle
|
||||||
black authentik tests lifecycle
|
black authentik tests scripts lifecycle
|
||||||
codespell -I .github/codespell-words.txt -S 'web/src/locales/**' -w \
|
codespell -I .github/codespell-words.txt -S 'web/src/locales/**' -w \
|
||||||
authentik \
|
authentik \
|
||||||
internal \
|
internal \
|
||||||
@ -36,65 +45,95 @@ lint-fix:
|
|||||||
website/developer-docs
|
website/developer-docs
|
||||||
|
|
||||||
lint:
|
lint:
|
||||||
bandit -r authentik tests lifecycle -x node_modules
|
|
||||||
pylint authentik tests lifecycle
|
pylint authentik tests lifecycle
|
||||||
|
bandit -r authentik tests lifecycle -x node_modules
|
||||||
golangci-lint run -v
|
golangci-lint run -v
|
||||||
|
|
||||||
i18n-extract: i18n-extract-core web-extract
|
|
||||||
|
|
||||||
i18n-extract-core:
|
|
||||||
./manage.py makemessages --ignore web --ignore internal --ignore web --ignore web-api --ignore website -l en
|
|
||||||
|
|
||||||
gen-build:
|
|
||||||
./manage.py spectacular --file schema.yml
|
|
||||||
|
|
||||||
gen-clean:
|
|
||||||
rm -rf web/api/src/
|
|
||||||
rm -rf api/
|
|
||||||
|
|
||||||
gen-web:
|
|
||||||
docker run \
|
|
||||||
--rm -v ${PWD}:/local \
|
|
||||||
--user ${UID}:${GID} \
|
|
||||||
openapitools/openapi-generator-cli generate \
|
|
||||||
-i /local/schema.yml \
|
|
||||||
-g typescript-fetch \
|
|
||||||
-o /local/web-api \
|
|
||||||
--additional-properties=typescriptThreePlus=true,supportsES6=true,npmName=@goauthentik/api,npmVersion=${NPM_VERSION}
|
|
||||||
mkdir -p web/node_modules/@goauthentik/api
|
|
||||||
python -m scripts.web_api_esm
|
|
||||||
\cp -fv scripts/web_api_readme.md web-api/README.md
|
|
||||||
cd web-api && npm i
|
|
||||||
\cp -rfv web-api/* web/node_modules/@goauthentik/api
|
|
||||||
|
|
||||||
gen-outpost:
|
|
||||||
wget https://raw.githubusercontent.com/goauthentik/client-go/main/config.yaml -O config.yaml
|
|
||||||
mkdir -p templates
|
|
||||||
wget https://raw.githubusercontent.com/goauthentik/client-go/main/templates/README.mustache -O templates/README.mustache
|
|
||||||
wget https://raw.githubusercontent.com/goauthentik/client-go/main/templates/go.mod.mustache -O templates/go.mod.mustache
|
|
||||||
docker run \
|
|
||||||
--rm -v ${PWD}:/local \
|
|
||||||
--user ${UID}:${GID} \
|
|
||||||
openapitools/openapi-generator-cli:v5.2.1 generate \
|
|
||||||
-i /local/schema.yml \
|
|
||||||
-g go \
|
|
||||||
-o /local/api \
|
|
||||||
-c /local/config.yaml
|
|
||||||
go mod edit -replace goauthentik.io/api=./api
|
|
||||||
rm -rf config.yaml ./templates/
|
|
||||||
|
|
||||||
gen: gen-build gen-clean gen-web
|
|
||||||
|
|
||||||
migrate:
|
migrate:
|
||||||
python -m lifecycle.migrate
|
python -m lifecycle.migrate
|
||||||
|
|
||||||
run:
|
run:
|
||||||
go run -v cmd/server/main.go
|
go run -v cmd/server/main.go
|
||||||
|
|
||||||
web-watch:
|
i18n-extract: i18n-extract-core web-extract
|
||||||
cd web && npm run watch
|
|
||||||
|
|
||||||
web: web-lint-fix web-lint web-extract
|
i18n-extract-core:
|
||||||
|
ak makemessages --ignore web --ignore internal --ignore web --ignore web-api --ignore website -l en
|
||||||
|
|
||||||
|
#########################
|
||||||
|
## API Schema
|
||||||
|
#########################
|
||||||
|
|
||||||
|
gen-build:
|
||||||
|
AUTHENTIK_DEBUG=true ak make_blueprint_schema > blueprints/schema.json
|
||||||
|
AUTHENTIK_DEBUG=true ak spectacular --file schema.yml
|
||||||
|
|
||||||
|
gen-diff:
|
||||||
|
git show $(shell git tag -l | tail -n 1):schema.yml > old_schema.yml
|
||||||
|
docker run \
|
||||||
|
--rm -v ${PWD}:/local \
|
||||||
|
--user ${UID}:${GID} \
|
||||||
|
docker.io/openapitools/openapi-diff:2.0.1 \
|
||||||
|
--markdown /local/diff.md \
|
||||||
|
/local/old_schema.yml /local/schema.yml
|
||||||
|
rm old_schema.yml
|
||||||
|
|
||||||
|
gen-clean:
|
||||||
|
rm -rf web/api/src/
|
||||||
|
rm -rf api/
|
||||||
|
|
||||||
|
gen-client-ts:
|
||||||
|
docker run \
|
||||||
|
--rm -v ${PWD}:/local \
|
||||||
|
--user ${UID}:${GID} \
|
||||||
|
docker.io/openapitools/openapi-generator-cli:v6.0.0 generate \
|
||||||
|
-i /local/schema.yml \
|
||||||
|
-g typescript-fetch \
|
||||||
|
-o /local/gen-ts-api \
|
||||||
|
--additional-properties=typescriptThreePlus=true,supportsES6=true,npmName=@goauthentik/api,npmVersion=${NPM_VERSION}
|
||||||
|
mkdir -p web/node_modules/@goauthentik/api
|
||||||
|
\cp -fv scripts/web_api_readme.md gen-ts-api/README.md
|
||||||
|
cd gen-ts-api && npm i
|
||||||
|
\cp -rfv gen-ts-api/* web/node_modules/@goauthentik/api
|
||||||
|
|
||||||
|
gen-client-go:
|
||||||
|
wget https://raw.githubusercontent.com/goauthentik/client-go/main/config.yaml -O config.yaml
|
||||||
|
mkdir -p templates
|
||||||
|
wget https://raw.githubusercontent.com/goauthentik/client-go/main/templates/README.mustache -O templates/README.mustache
|
||||||
|
wget https://raw.githubusercontent.com/goauthentik/client-go/main/templates/go.mod.mustache -O templates/go.mod.mustache
|
||||||
|
docker run \
|
||||||
|
--rm -v ${PWD}:/local \
|
||||||
|
--user ${UID}:${GID} \
|
||||||
|
docker.io/openapitools/openapi-generator-cli:v6.0.0 generate \
|
||||||
|
-i /local/schema.yml \
|
||||||
|
-g go \
|
||||||
|
-o /local/gen-go-api \
|
||||||
|
-c /local/config.yaml
|
||||||
|
go mod edit -replace goauthentik.io/api/v3=./gen-go-api
|
||||||
|
rm -rf config.yaml ./templates/
|
||||||
|
|
||||||
|
gen-dev-config:
|
||||||
|
python -m scripts.generate_config
|
||||||
|
|
||||||
|
gen: gen-build gen-clean gen-client-ts
|
||||||
|
|
||||||
|
#########################
|
||||||
|
## Web
|
||||||
|
#########################
|
||||||
|
|
||||||
|
web-build: web-install
|
||||||
|
cd web && npm run build
|
||||||
|
|
||||||
|
web: web-lint-fix web-lint
|
||||||
|
|
||||||
|
web-install:
|
||||||
|
cd web && npm ci
|
||||||
|
|
||||||
|
web-watch:
|
||||||
|
rm -rf web/dist/
|
||||||
|
mkdir web/dist/
|
||||||
|
touch web/dist/.gitkeep
|
||||||
|
cd web && npm run watch
|
||||||
|
|
||||||
web-lint-fix:
|
web-lint-fix:
|
||||||
cd web && npm run prettier
|
cd web && npm run prettier
|
||||||
@ -106,6 +145,21 @@ web-lint:
|
|||||||
web-extract:
|
web-extract:
|
||||||
cd web && npm run extract
|
cd web && npm run extract
|
||||||
|
|
||||||
|
#########################
|
||||||
|
## Website
|
||||||
|
#########################
|
||||||
|
|
||||||
|
website: website-lint-fix
|
||||||
|
|
||||||
|
website-install:
|
||||||
|
cd website && npm ci
|
||||||
|
|
||||||
|
website-lint-fix:
|
||||||
|
cd website && npm run prettier
|
||||||
|
|
||||||
|
website-watch:
|
||||||
|
cd website && npm run watch
|
||||||
|
|
||||||
# These targets are use by GitHub actions to allow usage of matrix
|
# These targets are use by GitHub actions to allow usage of matrix
|
||||||
# which makes the YAML File a lot smaller
|
# which makes the YAML File a lot smaller
|
||||||
|
|
||||||
@ -129,14 +183,16 @@ ci-pyright: ci--meta-debug
|
|||||||
pyright e2e lifecycle
|
pyright e2e lifecycle
|
||||||
|
|
||||||
ci-pending-migrations: ci--meta-debug
|
ci-pending-migrations: ci--meta-debug
|
||||||
./manage.py makemigrations --check
|
ak makemigrations --check
|
||||||
|
|
||||||
install:
|
install: web-install website-install
|
||||||
poetry install
|
poetry install
|
||||||
cd web && npm i
|
|
||||||
cd website && npm i
|
|
||||||
|
|
||||||
a: install
|
dev-reset:
|
||||||
tmux -CC \
|
dropdb -U postgres -h localhost authentik
|
||||||
new-session 'make run' \; \
|
createdb -U postgres -h localhost authentik
|
||||||
split-window 'make web-watch'
|
redis-cli -n 0 flushall
|
||||||
|
redis-cli -n 1 flushall
|
||||||
|
redis-cli -n 2 flushall
|
||||||
|
redis-cli -n 3 flushall
|
||||||
|
make migrate
|
||||||
|
@ -9,7 +9,7 @@
|
|||||||
[](https://github.com/goauthentik/authentik/actions/workflows/ci-outpost.yml)
|
[](https://github.com/goauthentik/authentik/actions/workflows/ci-outpost.yml)
|
||||||
[](https://github.com/goauthentik/authentik/actions/workflows/ci-web.yml)
|
[](https://github.com/goauthentik/authentik/actions/workflows/ci-web.yml)
|
||||||
[](https://codecov.io/gh/goauthentik/authentik)
|
[](https://codecov.io/gh/goauthentik/authentik)
|
||||||
[](https://goauthentik.testspace.com/)
|
[](https://goauthentik.testspace.com/)
|
||||||

|

|
||||||

|

|
||||||
[](https://www.transifex.com/beryjuorg/authentik/)
|
[](https://www.transifex.com/beryjuorg/authentik/)
|
||||||
|
@ -6,9 +6,10 @@
|
|||||||
|
|
||||||
| Version | Supported |
|
| Version | Supported |
|
||||||
| ---------- | ------------------ |
|
| ---------- | ------------------ |
|
||||||
| 2022.2.x | :white_check_mark: |
|
| 2022.6.x | :white_check_mark: |
|
||||||
| 2022.3.x | :white_check_mark: |
|
| 2022.7.x | :white_check_mark: |
|
||||||
|
| 2022.8.x | :white_check_mark: |
|
||||||
|
|
||||||
## Reporting a Vulnerability
|
## Reporting a Vulnerability
|
||||||
|
|
||||||
To report a vulnerability, send an email to [security@beryju.org](mailto:security@beryju.org)
|
To report a vulnerability, send an email to [security@goauthentik.io](mailto:security@goauthentik.io)
|
||||||
|
@ -2,13 +2,16 @@
|
|||||||
from os import environ
|
from os import environ
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
__version__ = "2022.3.2"
|
__version__ = "2022.8.2"
|
||||||
ENV_GIT_HASH_KEY = "GIT_BUILD_HASH"
|
ENV_GIT_HASH_KEY = "GIT_BUILD_HASH"
|
||||||
|
|
||||||
|
|
||||||
def get_build_hash(fallback: Optional[str] = None) -> str:
|
def get_build_hash(fallback: Optional[str] = None) -> str:
|
||||||
"""Get build hash"""
|
"""Get build hash"""
|
||||||
return environ.get(ENV_GIT_HASH_KEY, fallback if fallback else "")
|
build_hash = environ.get(ENV_GIT_HASH_KEY, fallback if fallback else "")
|
||||||
|
if build_hash == "" and fallback:
|
||||||
|
return fallback
|
||||||
|
return build_hash
|
||||||
|
|
||||||
|
|
||||||
def get_full_version() -> str:
|
def get_full_version() -> str:
|
||||||
|
@ -18,13 +18,13 @@ class AppSerializer(PassiveSerializer):
|
|||||||
|
|
||||||
|
|
||||||
class AppsViewSet(ViewSet):
|
class AppsViewSet(ViewSet):
|
||||||
"""Read-only view set list all installed apps"""
|
"""Read-only view list all installed apps"""
|
||||||
|
|
||||||
permission_classes = [IsAdminUser]
|
permission_classes = [IsAdminUser]
|
||||||
|
|
||||||
@extend_schema(responses={200: AppSerializer(many=True)})
|
@extend_schema(responses={200: AppSerializer(many=True)})
|
||||||
def list(self, request: Request) -> Response:
|
def list(self, request: Request) -> Response:
|
||||||
"""List current messages and pass into Serializer"""
|
"""Read-only view list all installed apps"""
|
||||||
data = []
|
data = []
|
||||||
for app in sorted(get_apps(), key=lambda app: app.name):
|
for app in sorted(get_apps(), key=lambda app: app.name):
|
||||||
data.append({"name": app.name, "label": app.verbose_name})
|
data.append({"name": app.name, "label": app.verbose_name})
|
||||||
|
@ -16,7 +16,7 @@ from rest_framework.response import Response
|
|||||||
from rest_framework.views import APIView
|
from rest_framework.views import APIView
|
||||||
|
|
||||||
from authentik.core.api.utils import PassiveSerializer
|
from authentik.core.api.utils import PassiveSerializer
|
||||||
from authentik.outposts.managed import MANAGED_OUTPOST
|
from authentik.outposts.apps import MANAGED_OUTPOST
|
||||||
from authentik.outposts.models import Outpost
|
from authentik.outposts.models import Outpost
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
"""authentik administration overview"""
|
"""authentik administration overview"""
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from drf_spectacular.utils import extend_schema, inline_serializer
|
from drf_spectacular.utils import extend_schema, inline_serializer
|
||||||
from prometheus_client import Gauge
|
|
||||||
from rest_framework.fields import IntegerField
|
from rest_framework.fields import IntegerField
|
||||||
from rest_framework.permissions import IsAdminUser
|
from rest_framework.permissions import IsAdminUser
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
@ -10,8 +9,6 @@ from rest_framework.views import APIView
|
|||||||
|
|
||||||
from authentik.root.celery import CELERY_APP
|
from authentik.root.celery import CELERY_APP
|
||||||
|
|
||||||
GAUGE_WORKERS = Gauge("authentik_admin_workers", "Currently connected workers")
|
|
||||||
|
|
||||||
|
|
||||||
class WorkerView(APIView):
|
class WorkerView(APIView):
|
||||||
"""Get currently connected worker count."""
|
"""Get currently connected worker count."""
|
||||||
|
@ -1,18 +1,20 @@
|
|||||||
"""authentik admin app config"""
|
"""authentik admin app config"""
|
||||||
from importlib import import_module
|
from prometheus_client import Gauge, Info
|
||||||
|
|
||||||
from django.apps import AppConfig
|
from authentik.blueprints.manager import ManagedAppConfig
|
||||||
|
|
||||||
|
PROM_INFO = Info("authentik_version", "Currently running authentik version")
|
||||||
|
GAUGE_WORKERS = Gauge("authentik_admin_workers", "Currently connected workers")
|
||||||
|
|
||||||
|
|
||||||
class AuthentikAdminConfig(AppConfig):
|
class AuthentikAdminConfig(ManagedAppConfig):
|
||||||
"""authentik admin app config"""
|
"""authentik admin app config"""
|
||||||
|
|
||||||
name = "authentik.admin"
|
name = "authentik.admin"
|
||||||
label = "authentik_admin"
|
label = "authentik_admin"
|
||||||
verbose_name = "authentik Admin"
|
verbose_name = "authentik Admin"
|
||||||
|
default = True
|
||||||
|
|
||||||
def ready(self):
|
def reconcile_load_admin_signals(self):
|
||||||
from authentik.admin.tasks import clear_update_notifications
|
"""Load admin signals"""
|
||||||
|
self.import_module("authentik.admin.signals")
|
||||||
clear_update_notifications.delay()
|
|
||||||
import_module("authentik.admin.signals")
|
|
||||||
|
@ -1,10 +1,12 @@
|
|||||||
"""authentik admin settings"""
|
"""authentik admin settings"""
|
||||||
from celery.schedules import crontab
|
from celery.schedules import crontab
|
||||||
|
|
||||||
|
from authentik.lib.utils.time import fqdn_rand
|
||||||
|
|
||||||
CELERY_BEAT_SCHEDULE = {
|
CELERY_BEAT_SCHEDULE = {
|
||||||
"admin_latest_version": {
|
"admin_latest_version": {
|
||||||
"task": "authentik.admin.tasks.update_latest_version",
|
"task": "authentik.admin.tasks.update_latest_version",
|
||||||
"schedule": crontab(minute="*/60"), # Run every hour
|
"schedule": crontab(minute=fqdn_rand("admin_latest_version"), hour="*"),
|
||||||
"options": {"queue": "authentik_scheduled"},
|
"options": {"queue": "authentik_scheduled"},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
from django.dispatch import receiver
|
from django.dispatch import receiver
|
||||||
|
|
||||||
from authentik.admin.api.tasks import TaskInfo
|
from authentik.admin.api.tasks import TaskInfo
|
||||||
from authentik.admin.api.workers import GAUGE_WORKERS
|
from authentik.admin.apps import GAUGE_WORKERS
|
||||||
from authentik.root.celery import CELERY_APP
|
from authentik.root.celery import CELERY_APP
|
||||||
from authentik.root.monitoring import monitoring_set
|
from authentik.root.monitoring import monitoring_set
|
||||||
|
|
||||||
|
@ -3,12 +3,13 @@ import re
|
|||||||
|
|
||||||
from django.core.cache import cache
|
from django.core.cache import cache
|
||||||
from django.core.validators import URLValidator
|
from django.core.validators import URLValidator
|
||||||
|
from django.db import DatabaseError, InternalError, ProgrammingError
|
||||||
from packaging.version import parse
|
from packaging.version import parse
|
||||||
from prometheus_client import Info
|
|
||||||
from requests import RequestException
|
from requests import RequestException
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik import __version__, get_build_hash
|
from authentik import __version__, get_build_hash
|
||||||
|
from authentik.admin.apps import PROM_INFO
|
||||||
from authentik.events.models import Event, EventAction, Notification
|
from authentik.events.models import Event, EventAction, Notification
|
||||||
from authentik.events.monitored_tasks import (
|
from authentik.events.monitored_tasks import (
|
||||||
MonitoredTask,
|
MonitoredTask,
|
||||||
@ -25,7 +26,6 @@ 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
|
||||||
URL_FINDER = URLValidator.regex.pattern[1:]
|
URL_FINDER = URLValidator.regex.pattern[1:]
|
||||||
PROM_INFO = Info("authentik_version", "Currently running authentik version")
|
|
||||||
LOCAL_VERSION = parse(__version__)
|
LOCAL_VERSION = parse(__version__)
|
||||||
|
|
||||||
|
|
||||||
@ -40,7 +40,9 @@ def _set_prom_info():
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@CELERY_APP.task()
|
@CELERY_APP.task(
|
||||||
|
throws=(DatabaseError, ProgrammingError, InternalError),
|
||||||
|
)
|
||||||
def clear_update_notifications():
|
def clear_update_notifications():
|
||||||
"""Clear update notifications on startup if the notification was for the version
|
"""Clear update notifications on startup if the notification was for the version
|
||||||
we're running now."""
|
we're running now."""
|
||||||
|
@ -5,10 +5,10 @@ from django.test import TestCase
|
|||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
|
|
||||||
from authentik import __version__
|
from authentik import __version__
|
||||||
|
from authentik.blueprints.tests import reconcile_app
|
||||||
from authentik.core.models import Group, User
|
from authentik.core.models import Group, User
|
||||||
from authentik.core.tasks import clean_expired_models
|
from authentik.core.tasks import clean_expired_models
|
||||||
from authentik.events.monitored_tasks import TaskResultStatus
|
from authentik.events.monitored_tasks import TaskResultStatus
|
||||||
from authentik.managed.tasks import managed_reconcile
|
|
||||||
|
|
||||||
|
|
||||||
class TestAdminAPI(TestCase):
|
class TestAdminAPI(TestCase):
|
||||||
@ -93,9 +93,8 @@ class TestAdminAPI(TestCase):
|
|||||||
response = self.client.get(reverse("authentik_api:apps-list"))
|
response = self.client.get(reverse("authentik_api:apps-list"))
|
||||||
self.assertEqual(response.status_code, 200)
|
self.assertEqual(response.status_code, 200)
|
||||||
|
|
||||||
|
@reconcile_app("authentik_outposts")
|
||||||
def test_system(self):
|
def test_system(self):
|
||||||
"""Test system API"""
|
"""Test system API"""
|
||||||
# pyright: reportGeneralTypeIssues=false
|
|
||||||
managed_reconcile() # pylint: disable=no-value-for-parameter
|
|
||||||
response = self.client.get(reverse("authentik_api:admin_system"))
|
response = self.client.get(reverse("authentik_api:admin_system"))
|
||||||
self.assertEqual(response.status_code, 200)
|
self.assertEqual(response.status_code, 200)
|
||||||
|
@ -26,7 +26,7 @@ class TestAdminTasks(TestCase):
|
|||||||
|
|
||||||
def test_version_valid_response(self):
|
def test_version_valid_response(self):
|
||||||
"""Test Update checker with valid response"""
|
"""Test Update checker with valid response"""
|
||||||
with Mocker() as mocker:
|
with Mocker() as mocker, CONFIG.patch("disable_update_check", False):
|
||||||
mocker.get("https://version.goauthentik.io/version.json", json=RESPONSE_VALID)
|
mocker.get("https://version.goauthentik.io/version.json", json=RESPONSE_VALID)
|
||||||
update_latest_version.delay().get()
|
update_latest_version.delay().get()
|
||||||
self.assertEqual(cache.get(VERSION_CACHE_KEY), "99999999.9999999")
|
self.assertEqual(cache.get(VERSION_CACHE_KEY), "99999999.9999999")
|
||||||
|
@ -1,6 +1,4 @@
|
|||||||
"""API Authentication"""
|
"""API Authentication"""
|
||||||
from base64 import b64decode
|
|
||||||
from binascii import Error
|
|
||||||
from typing import Any, Optional
|
from typing import Any, Optional
|
||||||
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
@ -9,59 +7,71 @@ from rest_framework.exceptions import AuthenticationFailed
|
|||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik.core.middleware import KEY_AUTH_VIA, LOCAL
|
from authentik.core.middleware import CTX_AUTH_VIA
|
||||||
from authentik.core.models import Token, TokenIntents, User
|
from authentik.core.models import Token, TokenIntents, User
|
||||||
from authentik.outposts.models import Outpost
|
from authentik.outposts.models import Outpost
|
||||||
|
from authentik.providers.oauth2.constants import SCOPE_AUTHENTIK_API
|
||||||
|
from authentik.providers.oauth2.models import RefreshToken
|
||||||
|
|
||||||
LOGGER = get_logger()
|
LOGGER = get_logger()
|
||||||
|
|
||||||
|
|
||||||
# pylint: disable=too-many-return-statements
|
def validate_auth(header: bytes) -> str:
|
||||||
def bearer_auth(raw_header: bytes) -> Optional[User]:
|
"""Validate that the header is in a correct format,
|
||||||
"""raw_header in the Format of `Bearer dGVzdDp0ZXN0`"""
|
returns type and credentials"""
|
||||||
auth_credentials = raw_header.decode()
|
auth_credentials = header.decode().strip()
|
||||||
if auth_credentials == "" or " " not in auth_credentials:
|
if auth_credentials == "" or " " not in auth_credentials:
|
||||||
return None
|
return None
|
||||||
auth_type, _, auth_credentials = auth_credentials.partition(" ")
|
auth_type, _, auth_credentials = auth_credentials.partition(" ")
|
||||||
if auth_type.lower() not in ["basic", "bearer"]:
|
if auth_type.lower() != "bearer":
|
||||||
LOGGER.debug("Unsupported authentication type, denying", type=auth_type.lower())
|
LOGGER.debug("Unsupported authentication type, denying", type=auth_type.lower())
|
||||||
raise AuthenticationFailed("Unsupported authentication type")
|
raise AuthenticationFailed("Unsupported authentication type")
|
||||||
password = auth_credentials
|
if auth_credentials == "": # nosec # noqa
|
||||||
if auth_type.lower() == "basic":
|
|
||||||
try:
|
|
||||||
auth_credentials = b64decode(auth_credentials.encode()).decode()
|
|
||||||
except (UnicodeDecodeError, Error):
|
|
||||||
raise AuthenticationFailed("Malformed header")
|
|
||||||
# Accept credentials with username and without
|
|
||||||
if ":" in auth_credentials:
|
|
||||||
_, _, password = auth_credentials.partition(":")
|
|
||||||
else:
|
|
||||||
password = auth_credentials
|
|
||||||
if password == "": # nosec
|
|
||||||
raise AuthenticationFailed("Malformed header")
|
raise AuthenticationFailed("Malformed header")
|
||||||
tokens = Token.filter_not_expired(key=password, intent=TokenIntents.INTENT_API)
|
return auth_credentials
|
||||||
if not tokens.exists():
|
|
||||||
user = token_secret_key(password)
|
|
||||||
if not user:
|
def bearer_auth(raw_header: bytes) -> Optional[User]:
|
||||||
|
"""raw_header in the Format of `Bearer ....`"""
|
||||||
|
auth_credentials = validate_auth(raw_header)
|
||||||
|
if not auth_credentials:
|
||||||
|
return None
|
||||||
|
# first, check traditional tokens
|
||||||
|
key_token = Token.filter_not_expired(
|
||||||
|
key=auth_credentials, intent=TokenIntents.INTENT_API
|
||||||
|
).first()
|
||||||
|
if key_token:
|
||||||
|
CTX_AUTH_VIA.set("api_token")
|
||||||
|
return key_token.user
|
||||||
|
# then try to auth via JWT
|
||||||
|
jwt_token = RefreshToken.filter_not_expired(
|
||||||
|
refresh_token=auth_credentials, _scope__icontains=SCOPE_AUTHENTIK_API
|
||||||
|
).first()
|
||||||
|
if jwt_token:
|
||||||
|
# Double-check scopes, since they are saved in a single string
|
||||||
|
# we want to check the parsed version too
|
||||||
|
if SCOPE_AUTHENTIK_API not in jwt_token.scope:
|
||||||
raise AuthenticationFailed("Token invalid/expired")
|
raise AuthenticationFailed("Token invalid/expired")
|
||||||
|
CTX_AUTH_VIA.set("jwt")
|
||||||
|
return jwt_token.user
|
||||||
|
# then try to auth via secret key (for embedded outpost/etc)
|
||||||
|
user = token_secret_key(auth_credentials)
|
||||||
|
if user:
|
||||||
|
CTX_AUTH_VIA.set("secret_key")
|
||||||
return user
|
return user
|
||||||
if hasattr(LOCAL, "authentik"):
|
raise AuthenticationFailed("Token invalid/expired")
|
||||||
LOCAL.authentik[KEY_AUTH_VIA] = "api_token"
|
|
||||||
return tokens.first().user
|
|
||||||
|
|
||||||
|
|
||||||
def token_secret_key(value: str) -> Optional[User]:
|
def token_secret_key(value: str) -> Optional[User]:
|
||||||
"""Check if the token is the secret key
|
"""Check if the token is the secret key
|
||||||
and return the service account for the managed outpost"""
|
and return the service account for the managed outpost"""
|
||||||
from authentik.outposts.managed import MANAGED_OUTPOST
|
from authentik.outposts.apps import MANAGED_OUTPOST
|
||||||
|
|
||||||
if value != settings.SECRET_KEY:
|
if value != settings.SECRET_KEY:
|
||||||
return None
|
return None
|
||||||
outposts = Outpost.objects.filter(managed=MANAGED_OUTPOST)
|
outposts = Outpost.objects.filter(managed=MANAGED_OUTPOST)
|
||||||
if not outposts:
|
if not outposts:
|
||||||
return None
|
return None
|
||||||
if hasattr(LOCAL, "authentik"):
|
|
||||||
LOCAL.authentik[KEY_AUTH_VIA] = "secret_key"
|
|
||||||
outpost = outposts.first()
|
outpost = outposts.first()
|
||||||
return outpost.user
|
return outpost.user
|
||||||
|
|
||||||
|
@ -12,6 +12,8 @@ class OwnerFilter(BaseFilterBackend):
|
|||||||
owner_key = "user"
|
owner_key = "user"
|
||||||
|
|
||||||
def filter_queryset(self, request: Request, queryset: QuerySet, view) -> QuerySet:
|
def filter_queryset(self, request: Request, queryset: QuerySet, view) -> QuerySet:
|
||||||
|
if request.user.is_superuser:
|
||||||
|
return queryset
|
||||||
return queryset.filter(**{self.owner_key: request.user})
|
return queryset.filter(**{self.owner_key: request.user})
|
||||||
|
|
||||||
|
|
||||||
|
@ -60,8 +60,28 @@ def postprocess_schema_responses(result, generator, **kwargs): # noqa: W0613
|
|||||||
|
|
||||||
for path in result["paths"].values():
|
for path in result["paths"].values():
|
||||||
for method in path.values():
|
for method in path.values():
|
||||||
method["responses"].setdefault("400", validation_error.ref)
|
method["responses"].setdefault(
|
||||||
method["responses"].setdefault("403", generic_error.ref)
|
"400",
|
||||||
|
{
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": validation_error.ref,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"description": "",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
method["responses"].setdefault(
|
||||||
|
"403",
|
||||||
|
{
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": generic_error.ref,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"description": "",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
result["components"] = generator.registry.build(spectacular_settings.APPEND_COMPONENTS)
|
result["components"] = generator.registry.build(spectacular_settings.APPEND_COMPONENTS)
|
||||||
|
|
||||||
|
@ -8,9 +8,6 @@ API Browser - {{ tenant.branding_title }}
|
|||||||
|
|
||||||
{% block head %}
|
{% block head %}
|
||||||
<script type="module" src="{% static 'dist/rapidoc-min.js' %}"></script>
|
<script type="module" src="{% static 'dist/rapidoc-min.js' %}"></script>
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block body %}
|
|
||||||
<script>
|
<script>
|
||||||
function getCookie(name) {
|
function getCookie(name) {
|
||||||
let cookieValue = "";
|
let cookieValue = "";
|
||||||
@ -34,16 +31,58 @@ window.addEventListener('DOMContentLoaded', (event) => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
<style>
|
||||||
|
img.logo {
|
||||||
|
width: 100%;
|
||||||
|
padding: 1rem 0.5rem 1.5rem 0.5rem;
|
||||||
|
min-height: 48px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block body %}
|
||||||
<rapi-doc
|
<rapi-doc
|
||||||
spec-url="{{ path }}"
|
spec-url="{{ path }}"
|
||||||
heading-text="authentik"
|
heading-text=""
|
||||||
theme="dark"
|
theme="light"
|
||||||
render-style="view"
|
render-style="read"
|
||||||
|
default-schema-tab="schema"
|
||||||
primary-color="#fd4b2d"
|
primary-color="#fd4b2d"
|
||||||
|
nav-bg-color="#212427"
|
||||||
|
bg-color="#000000"
|
||||||
|
text-color="#000000"
|
||||||
|
nav-text-color="#ffffff"
|
||||||
|
nav-hover-bg-color="#3c3f42"
|
||||||
|
nav-accent-color="#4f5255"
|
||||||
|
nav-hover-text-color="#ffffff"
|
||||||
|
use-path-in-nav-bar="true"
|
||||||
|
nav-item-spacing="relaxed"
|
||||||
|
allow-server-selection="false"
|
||||||
|
show-header="false"
|
||||||
allow-spec-url-load="false"
|
allow-spec-url-load="false"
|
||||||
allow-spec-file-load="false">
|
allow-spec-file-load="false">
|
||||||
<div slot="logo">
|
<div slot="nav-logo">
|
||||||
<img src="{% static 'dist/assets/icons/icon.png' %}" style="width:50px; height:50px" />
|
<img class="logo" src="{% static 'dist/assets/icons/icon_left_brand.png' %}" />
|
||||||
</div>
|
</div>
|
||||||
</rapi-doc>
|
</rapi-doc>
|
||||||
|
<script>
|
||||||
|
const rapidoc = document.querySelector("rapi-doc");
|
||||||
|
const matcher = window.matchMedia("(prefers-color-scheme: light)");
|
||||||
|
const changer = (ev) => {
|
||||||
|
const style = getComputedStyle(document.documentElement);
|
||||||
|
let bg, text = "";
|
||||||
|
if (matcher.matches) {
|
||||||
|
bg = style.getPropertyValue('--pf-global--BackgroundColor--light-300');
|
||||||
|
text = style.getPropertyValue('--pf-global--Color--300');
|
||||||
|
} else {
|
||||||
|
bg = style.getPropertyValue('--ak-dark-background');
|
||||||
|
text = style.getPropertyValue('--ak-dark-foreground');
|
||||||
|
}
|
||||||
|
rapidoc.attributes.getNamedItem("bg-color").value = bg.trim();
|
||||||
|
rapidoc.attributes.getNamedItem("text-color").value = text.trim();
|
||||||
|
rapidoc.requestUpdate();
|
||||||
|
};
|
||||||
|
matcher.addEventListener("change", changer);
|
||||||
|
window.addEventListener("load", changer);
|
||||||
|
</script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
@ -7,38 +7,26 @@ from guardian.shortcuts import get_anonymous_user
|
|||||||
from rest_framework.exceptions import AuthenticationFailed
|
from rest_framework.exceptions import AuthenticationFailed
|
||||||
|
|
||||||
from authentik.api.authentication import bearer_auth
|
from authentik.api.authentication import bearer_auth
|
||||||
|
from authentik.blueprints.tests import reconcile_app
|
||||||
from authentik.core.models import USER_ATTRIBUTE_SA, Token, TokenIntents
|
from authentik.core.models import USER_ATTRIBUTE_SA, Token, TokenIntents
|
||||||
from authentik.outposts.managed import OutpostManager
|
from authentik.core.tests.utils import create_test_flow
|
||||||
|
from authentik.lib.generators import generate_id
|
||||||
|
from authentik.providers.oauth2.constants import SCOPE_AUTHENTIK_API
|
||||||
|
from authentik.providers.oauth2.models import OAuth2Provider, RefreshToken
|
||||||
|
|
||||||
|
|
||||||
class TestAPIAuth(TestCase):
|
class TestAPIAuth(TestCase):
|
||||||
"""Test API Authentication"""
|
"""Test API Authentication"""
|
||||||
|
|
||||||
def test_valid_basic(self):
|
|
||||||
"""Test valid token"""
|
|
||||||
token = Token.objects.create(intent=TokenIntents.INTENT_API, user=get_anonymous_user())
|
|
||||||
auth = b64encode(f":{token.key}".encode()).decode()
|
|
||||||
self.assertEqual(bearer_auth(f"Basic {auth}".encode()), token.user)
|
|
||||||
|
|
||||||
def test_valid_bearer(self):
|
|
||||||
"""Test valid token"""
|
|
||||||
token = Token.objects.create(intent=TokenIntents.INTENT_API, user=get_anonymous_user())
|
|
||||||
self.assertEqual(bearer_auth(f"Bearer {token.key}".encode()), token.user)
|
|
||||||
|
|
||||||
def test_invalid_type(self):
|
def test_invalid_type(self):
|
||||||
"""Test invalid type"""
|
"""Test invalid type"""
|
||||||
with self.assertRaises(AuthenticationFailed):
|
with self.assertRaises(AuthenticationFailed):
|
||||||
bearer_auth("foo bar".encode())
|
bearer_auth("foo bar".encode())
|
||||||
|
|
||||||
def test_invalid_decode(self):
|
def test_invalid_empty(self):
|
||||||
"""Test invalid bas64"""
|
"""Test invalid type"""
|
||||||
with self.assertRaises(AuthenticationFailed):
|
self.assertIsNone(bearer_auth("Bearer ".encode()))
|
||||||
bearer_auth("Basic bar".encode())
|
self.assertIsNone(bearer_auth("".encode()))
|
||||||
|
|
||||||
def test_invalid_empty_password(self):
|
|
||||||
"""Test invalid with empty password"""
|
|
||||||
with self.assertRaises(AuthenticationFailed):
|
|
||||||
bearer_auth("Basic :".encode())
|
|
||||||
|
|
||||||
def test_invalid_no_token(self):
|
def test_invalid_no_token(self):
|
||||||
"""Test invalid with no token"""
|
"""Test invalid with no token"""
|
||||||
@ -46,11 +34,45 @@ class TestAPIAuth(TestCase):
|
|||||||
auth = b64encode(":abc".encode()).decode()
|
auth = b64encode(":abc".encode()).decode()
|
||||||
self.assertIsNone(bearer_auth(f"Basic :{auth}".encode()))
|
self.assertIsNone(bearer_auth(f"Basic :{auth}".encode()))
|
||||||
|
|
||||||
|
def test_bearer_valid(self):
|
||||||
|
"""Test valid token"""
|
||||||
|
token = Token.objects.create(intent=TokenIntents.INTENT_API, user=get_anonymous_user())
|
||||||
|
self.assertEqual(bearer_auth(f"Bearer {token.key}".encode()), token.user)
|
||||||
|
|
||||||
def test_managed_outpost(self):
|
def test_managed_outpost(self):
|
||||||
"""Test managed outpost"""
|
"""Test managed outpost"""
|
||||||
with self.assertRaises(AuthenticationFailed):
|
with self.assertRaises(AuthenticationFailed):
|
||||||
user = bearer_auth(f"Bearer {settings.SECRET_KEY}".encode())
|
bearer_auth(f"Bearer {settings.SECRET_KEY}".encode())
|
||||||
|
|
||||||
OutpostManager().run()
|
@reconcile_app("authentik_outposts")
|
||||||
|
def test_managed_outpost_success(self):
|
||||||
|
"""Test managed outpost"""
|
||||||
user = bearer_auth(f"Bearer {settings.SECRET_KEY}".encode())
|
user = bearer_auth(f"Bearer {settings.SECRET_KEY}".encode())
|
||||||
self.assertEqual(user.attributes[USER_ATTRIBUTE_SA], True)
|
self.assertEqual(user.attributes[USER_ATTRIBUTE_SA], True)
|
||||||
|
|
||||||
|
def test_jwt_valid(self):
|
||||||
|
"""Test valid JWT"""
|
||||||
|
provider = OAuth2Provider.objects.create(
|
||||||
|
name=generate_id(), client_id=generate_id(), authorization_flow=create_test_flow()
|
||||||
|
)
|
||||||
|
refresh = RefreshToken.objects.create(
|
||||||
|
user=get_anonymous_user(),
|
||||||
|
provider=provider,
|
||||||
|
refresh_token=generate_id(),
|
||||||
|
_scope=SCOPE_AUTHENTIK_API,
|
||||||
|
)
|
||||||
|
self.assertEqual(bearer_auth(f"Bearer {refresh.refresh_token}".encode()), refresh.user)
|
||||||
|
|
||||||
|
def test_jwt_missing_scope(self):
|
||||||
|
"""Test valid JWT"""
|
||||||
|
provider = OAuth2Provider.objects.create(
|
||||||
|
name=generate_id(), client_id=generate_id(), authorization_flow=create_test_flow()
|
||||||
|
)
|
||||||
|
refresh = RefreshToken.objects.create(
|
||||||
|
user=get_anonymous_user(),
|
||||||
|
provider=provider,
|
||||||
|
refresh_token=generate_id(),
|
||||||
|
_scope="",
|
||||||
|
)
|
||||||
|
with self.assertRaises(AuthenticationFailed):
|
||||||
|
self.assertEqual(bearer_auth(f"Bearer {refresh.refresh_token}".encode()), refresh.user)
|
||||||
|
29
authentik/api/tests/test_viewsets.py
Normal file
29
authentik/api/tests/test_viewsets.py
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
"""authentik API Modelviewset tests"""
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
from django.test import TestCase
|
||||||
|
from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet
|
||||||
|
|
||||||
|
from authentik.api.v3.urls import router
|
||||||
|
|
||||||
|
|
||||||
|
class TestModelViewSets(TestCase):
|
||||||
|
"""Test Viewset"""
|
||||||
|
|
||||||
|
|
||||||
|
def viewset_tester_factory(test_viewset: type[ModelViewSet]) -> Callable:
|
||||||
|
"""Test Viewset"""
|
||||||
|
|
||||||
|
def tester(self: TestModelViewSets):
|
||||||
|
self.assertIsNotNone(getattr(test_viewset, "search_fields", None))
|
||||||
|
filterset_class = getattr(test_viewset, "filterset_class", None)
|
||||||
|
if not filterset_class:
|
||||||
|
self.assertIsNotNone(getattr(test_viewset, "filterset_fields", None))
|
||||||
|
|
||||||
|
return tester
|
||||||
|
|
||||||
|
|
||||||
|
for _, viewset, _ in router.registry:
|
||||||
|
if not issubclass(viewset, (ModelViewSet, ReadOnlyModelViewSet)):
|
||||||
|
continue
|
||||||
|
setattr(TestModelViewSets, f"test_viewset_{viewset.__name__}", viewset_tester_factory(viewset))
|
@ -27,6 +27,7 @@ class Capabilities(models.TextChoices):
|
|||||||
|
|
||||||
CAN_SAVE_MEDIA = "can_save_media"
|
CAN_SAVE_MEDIA = "can_save_media"
|
||||||
CAN_GEO_IP = "can_geo_ip"
|
CAN_GEO_IP = "can_geo_ip"
|
||||||
|
CAN_IMPERSONATE = "can_impersonate"
|
||||||
|
|
||||||
|
|
||||||
class ErrorReportingConfigSerializer(PassiveSerializer):
|
class ErrorReportingConfigSerializer(PassiveSerializer):
|
||||||
@ -63,15 +64,16 @@ class ConfigView(APIView):
|
|||||||
caps.append(Capabilities.CAN_SAVE_MEDIA)
|
caps.append(Capabilities.CAN_SAVE_MEDIA)
|
||||||
if GEOIP_READER.enabled:
|
if GEOIP_READER.enabled:
|
||||||
caps.append(Capabilities.CAN_GEO_IP)
|
caps.append(Capabilities.CAN_GEO_IP)
|
||||||
|
if CONFIG.y_bool("impersonation"):
|
||||||
|
caps.append(Capabilities.CAN_IMPERSONATE)
|
||||||
return caps
|
return caps
|
||||||
|
|
||||||
@extend_schema(responses={200: ConfigSerializer(many=False)})
|
def get_config(self) -> ConfigSerializer:
|
||||||
def get(self, request: Request) -> Response:
|
"""Get Config"""
|
||||||
"""Retrieve public configuration options"""
|
return ConfigSerializer(
|
||||||
config = ConfigSerializer(
|
|
||||||
{
|
{
|
||||||
"error_reporting": {
|
"error_reporting": {
|
||||||
"enabled": CONFIG.y("error_reporting.enabled") and not settings.DEBUG,
|
"enabled": CONFIG.y("error_reporting.enabled"),
|
||||||
"environment": CONFIG.y("error_reporting.environment"),
|
"environment": CONFIG.y("error_reporting.environment"),
|
||||||
"send_pii": CONFIG.y("error_reporting.send_pii"),
|
"send_pii": CONFIG.y("error_reporting.send_pii"),
|
||||||
"traces_sample_rate": float(CONFIG.y("error_reporting.sample_rate", 0.4)),
|
"traces_sample_rate": float(CONFIG.y("error_reporting.sample_rate", 0.4)),
|
||||||
@ -83,4 +85,8 @@ class ConfigView(APIView):
|
|||||||
"cache_timeout_reputation": int(CONFIG.y("redis.cache_timeout_reputation")),
|
"cache_timeout_reputation": int(CONFIG.y("redis.cache_timeout_reputation")),
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
return Response(config.data)
|
|
||||||
|
@extend_schema(responses={200: ConfigSerializer(many=False)})
|
||||||
|
def get(self, request: Request) -> Response:
|
||||||
|
"""Retrieve public configuration options"""
|
||||||
|
return Response(self.get_config().data)
|
||||||
|
@ -12,9 +12,10 @@ from authentik.admin.api.version import VersionView
|
|||||||
from authentik.admin.api.workers import WorkerView
|
from authentik.admin.api.workers import WorkerView
|
||||||
from authentik.api.v3.config import ConfigView
|
from authentik.api.v3.config import ConfigView
|
||||||
from authentik.api.views import APIBrowserView
|
from authentik.api.views import APIBrowserView
|
||||||
|
from authentik.blueprints.api import BlueprintInstanceViewSet
|
||||||
from authentik.core.api.applications import ApplicationViewSet
|
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 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.propertymappings import PropertyMappingViewSet
|
||||||
from authentik.core.api.providers import ProviderViewSet
|
from authentik.core.api.providers import ProviderViewSet
|
||||||
@ -22,11 +23,11 @@ from authentik.core.api.sources import SourceViewSet, UserSourceConnectionViewSe
|
|||||||
from authentik.core.api.tokens import TokenViewSet
|
from authentik.core.api.tokens import TokenViewSet
|
||||||
from authentik.core.api.users import UserViewSet
|
from authentik.core.api.users import UserViewSet
|
||||||
from authentik.crypto.api import CertificateKeyPairViewSet
|
from authentik.crypto.api import CertificateKeyPairViewSet
|
||||||
from authentik.events.api.event import EventViewSet
|
from authentik.events.api.events import EventViewSet
|
||||||
from authentik.events.api.notification import NotificationViewSet
|
from authentik.events.api.notification_mappings import NotificationWebhookMappingViewSet
|
||||||
from authentik.events.api.notification_mapping import NotificationWebhookMappingViewSet
|
from authentik.events.api.notification_rules import NotificationRuleViewSet
|
||||||
from authentik.events.api.notification_rule import NotificationRuleViewSet
|
from authentik.events.api.notification_transports import NotificationTransportViewSet
|
||||||
from authentik.events.api.notification_transport import NotificationTransportViewSet
|
from authentik.events.api.notifications import NotificationViewSet
|
||||||
from authentik.flows.api.bindings import FlowStageBindingViewSet
|
from authentik.flows.api.bindings import FlowStageBindingViewSet
|
||||||
from authentik.flows.api.flows import FlowViewSet
|
from authentik.flows.api.flows import FlowViewSet
|
||||||
from authentik.flows.api.stages import StageViewSet
|
from authentik.flows.api.stages import StageViewSet
|
||||||
@ -131,6 +132,8 @@ router.register("events/notifications", NotificationViewSet)
|
|||||||
router.register("events/transports", NotificationTransportViewSet)
|
router.register("events/transports", NotificationTransportViewSet)
|
||||||
router.register("events/rules", NotificationRuleViewSet)
|
router.register("events/rules", NotificationRuleViewSet)
|
||||||
|
|
||||||
|
router.register("managed/blueprints", BlueprintInstanceViewSet)
|
||||||
|
|
||||||
router.register("sources/all", SourceViewSet)
|
router.register("sources/all", SourceViewSet)
|
||||||
router.register("sources/user_connections/all", UserSourceConnectionViewSet)
|
router.register("sources/user_connections/all", UserSourceConnectionViewSet)
|
||||||
router.register("sources/user_connections/oauth", UserOAuthSourceConnectionViewSet)
|
router.register("sources/user_connections/oauth", UserOAuthSourceConnectionViewSet)
|
||||||
@ -171,6 +174,11 @@ router.register("authenticators/sms", SMSDeviceViewSet)
|
|||||||
router.register("authenticators/static", StaticDeviceViewSet)
|
router.register("authenticators/static", StaticDeviceViewSet)
|
||||||
router.register("authenticators/totp", TOTPDeviceViewSet)
|
router.register("authenticators/totp", TOTPDeviceViewSet)
|
||||||
router.register("authenticators/webauthn", WebAuthnDeviceViewSet)
|
router.register("authenticators/webauthn", WebAuthnDeviceViewSet)
|
||||||
|
router.register(
|
||||||
|
"authenticators/admin/all",
|
||||||
|
AdminDeviceViewSet,
|
||||||
|
basename="admin-device",
|
||||||
|
)
|
||||||
router.register(
|
router.register(
|
||||||
"authenticators/admin/duo",
|
"authenticators/admin/duo",
|
||||||
DuoAdminDeviceViewSet,
|
DuoAdminDeviceViewSet,
|
||||||
|
109
authentik/blueprints/api.py
Normal file
109
authentik/blueprints/api.py
Normal file
@ -0,0 +1,109 @@
|
|||||||
|
"""Serializer mixin for managed models"""
|
||||||
|
from drf_spectacular.utils import extend_schema, inline_serializer
|
||||||
|
from rest_framework.decorators import action
|
||||||
|
from rest_framework.exceptions import ValidationError
|
||||||
|
from rest_framework.fields import CharField, DateTimeField, JSONField
|
||||||
|
from rest_framework.permissions import IsAdminUser
|
||||||
|
from rest_framework.request import Request
|
||||||
|
from rest_framework.response import Response
|
||||||
|
from rest_framework.serializers import ListSerializer, ModelSerializer
|
||||||
|
from rest_framework.viewsets import ModelViewSet
|
||||||
|
|
||||||
|
from authentik.api.decorators import permission_required
|
||||||
|
from authentik.blueprints.models import BlueprintInstance, BlueprintRetrievalFailed
|
||||||
|
from authentik.blueprints.v1.tasks import apply_blueprint, blueprints_find_dict
|
||||||
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
|
from authentik.core.api.utils import PassiveSerializer
|
||||||
|
|
||||||
|
|
||||||
|
class ManagedSerializer:
|
||||||
|
"""Managed Serializer"""
|
||||||
|
|
||||||
|
managed = CharField(read_only=True, allow_null=True)
|
||||||
|
|
||||||
|
|
||||||
|
class MetadataSerializer(PassiveSerializer):
|
||||||
|
"""Serializer for blueprint metadata"""
|
||||||
|
|
||||||
|
name = CharField()
|
||||||
|
labels = JSONField()
|
||||||
|
|
||||||
|
|
||||||
|
class BlueprintInstanceSerializer(ModelSerializer):
|
||||||
|
"""Info about a single blueprint instance file"""
|
||||||
|
|
||||||
|
def validate_path(self, path: str) -> str:
|
||||||
|
"""Ensure the path specified is retrievable"""
|
||||||
|
try:
|
||||||
|
BlueprintInstance(path=path).retrieve()
|
||||||
|
except BlueprintRetrievalFailed as exc:
|
||||||
|
raise ValidationError(exc) from exc
|
||||||
|
return path
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
|
||||||
|
model = BlueprintInstance
|
||||||
|
fields = [
|
||||||
|
"pk",
|
||||||
|
"name",
|
||||||
|
"path",
|
||||||
|
"context",
|
||||||
|
"last_applied",
|
||||||
|
"last_applied_hash",
|
||||||
|
"status",
|
||||||
|
"enabled",
|
||||||
|
"managed_models",
|
||||||
|
"metadata",
|
||||||
|
]
|
||||||
|
extra_kwargs = {
|
||||||
|
"status": {"read_only": True},
|
||||||
|
"last_applied": {"read_only": True},
|
||||||
|
"last_applied_hash": {"read_only": True},
|
||||||
|
"managed_models": {"read_only": True},
|
||||||
|
"metadata": {"read_only": True},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class BlueprintInstanceViewSet(UsedByMixin, ModelViewSet):
|
||||||
|
"""Blueprint instances"""
|
||||||
|
|
||||||
|
permission_classes = [IsAdminUser]
|
||||||
|
serializer_class = BlueprintInstanceSerializer
|
||||||
|
queryset = BlueprintInstance.objects.all()
|
||||||
|
search_fields = ["name", "path"]
|
||||||
|
filterset_fields = ["name", "path"]
|
||||||
|
|
||||||
|
@extend_schema(
|
||||||
|
responses={
|
||||||
|
200: ListSerializer(
|
||||||
|
child=inline_serializer(
|
||||||
|
"BlueprintFile",
|
||||||
|
fields={
|
||||||
|
"path": CharField(),
|
||||||
|
"last_m": DateTimeField(),
|
||||||
|
"hash": CharField(),
|
||||||
|
"meta": MetadataSerializer(required=False, read_only=True),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
@action(detail=False, pagination_class=None, filter_backends=[])
|
||||||
|
def available(self, request: Request) -> Response:
|
||||||
|
"""Get blueprints"""
|
||||||
|
files: list[dict] = blueprints_find_dict.delay().get()
|
||||||
|
return Response(files)
|
||||||
|
|
||||||
|
@permission_required("authentik_blueprints.view_blueprintinstance")
|
||||||
|
@extend_schema(
|
||||||
|
request=None,
|
||||||
|
responses={
|
||||||
|
200: BlueprintInstanceSerializer(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
@action(detail=True, pagination_class=None, filter_backends=[], methods=["POST"])
|
||||||
|
def apply(self, request: Request, *args, **kwargs) -> Response:
|
||||||
|
"""Apply a blueprint"""
|
||||||
|
blueprint = self.get_object()
|
||||||
|
apply_blueprint.delay(str(blueprint.pk)).get()
|
||||||
|
return self.retrieve(request, *args, **kwargs)
|
22
authentik/blueprints/apps.py
Normal file
22
authentik/blueprints/apps.py
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
"""authentik Blueprints app"""
|
||||||
|
|
||||||
|
from authentik.blueprints.manager import ManagedAppConfig
|
||||||
|
|
||||||
|
|
||||||
|
class AuthentikBlueprintsConfig(ManagedAppConfig):
|
||||||
|
"""authentik Blueprints app"""
|
||||||
|
|
||||||
|
name = "authentik.blueprints"
|
||||||
|
label = "authentik_blueprints"
|
||||||
|
verbose_name = "authentik Blueprints"
|
||||||
|
default = True
|
||||||
|
|
||||||
|
def reconcile_load_blueprints_v1_tasks(self):
|
||||||
|
"""Load v1 tasks"""
|
||||||
|
self.import_module("authentik.blueprints.v1.tasks")
|
||||||
|
|
||||||
|
def reconcile_blueprints_discover(self):
|
||||||
|
"""Run blueprint discovery"""
|
||||||
|
from authentik.blueprints.v1.tasks import blueprints_discover
|
||||||
|
|
||||||
|
blueprints_discover.delay()
|
28
authentik/blueprints/management/commands/apply_blueprint.py
Normal file
28
authentik/blueprints/management/commands/apply_blueprint.py
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
"""Apply blueprint from commandline"""
|
||||||
|
from django.core.management.base import BaseCommand, no_translations
|
||||||
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
|
from authentik.blueprints.models import BlueprintInstance
|
||||||
|
from authentik.blueprints.v1.importer import Importer
|
||||||
|
|
||||||
|
LOGGER = get_logger()
|
||||||
|
|
||||||
|
|
||||||
|
class Command(BaseCommand):
|
||||||
|
"""Apply blueprint from commandline"""
|
||||||
|
|
||||||
|
@no_translations
|
||||||
|
def handle(self, *args, **options):
|
||||||
|
"""Apply all blueprints in order, abort when one fails to import"""
|
||||||
|
for blueprint_path in options.get("blueprints", []):
|
||||||
|
content = BlueprintInstance(path=blueprint_path).retrieve()
|
||||||
|
importer = Importer(content)
|
||||||
|
valid, logs = importer.validate()
|
||||||
|
if not valid:
|
||||||
|
for log in logs:
|
||||||
|
LOGGER.debug(**log)
|
||||||
|
raise ValueError("blueprint invalid")
|
||||||
|
importer.apply()
|
||||||
|
|
||||||
|
def add_arguments(self, parser):
|
||||||
|
parser.add_argument("blueprints", nargs="+", type=str)
|
17
authentik/blueprints/management/commands/export_blueprint.py
Normal file
17
authentik/blueprints/management/commands/export_blueprint.py
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
"""Export blueprint of current authentik install"""
|
||||||
|
from django.core.management.base import BaseCommand, no_translations
|
||||||
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
|
from authentik.blueprints.v1.exporter import Exporter
|
||||||
|
|
||||||
|
LOGGER = get_logger()
|
||||||
|
|
||||||
|
|
||||||
|
class Command(BaseCommand):
|
||||||
|
"""Export blueprint of current authentik install"""
|
||||||
|
|
||||||
|
@no_translations
|
||||||
|
def handle(self, *args, **options):
|
||||||
|
"""Export blueprint of current authentik install"""
|
||||||
|
exporter = Exporter()
|
||||||
|
self.stdout.write(exporter.export_to_string())
|
@ -0,0 +1,38 @@
|
|||||||
|
"""Generate JSON Schema for blueprints"""
|
||||||
|
from json import dumps, loads
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from django.apps import apps
|
||||||
|
from django.core.management.base import BaseCommand, no_translations
|
||||||
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
|
from authentik.blueprints.v1.importer import is_model_allowed
|
||||||
|
from authentik.lib.models import SerializerModel
|
||||||
|
|
||||||
|
LOGGER = get_logger()
|
||||||
|
|
||||||
|
|
||||||
|
class Command(BaseCommand):
|
||||||
|
"""Generate JSON Schema for blueprints"""
|
||||||
|
|
||||||
|
schema: dict
|
||||||
|
|
||||||
|
@no_translations
|
||||||
|
def handle(self, *args, **options):
|
||||||
|
"""Generate JSON Schema for blueprints"""
|
||||||
|
path = Path(__file__).parent.joinpath("./schema_template.json")
|
||||||
|
with open(path, "r", encoding="utf-8") as _template_file:
|
||||||
|
self.schema = loads(_template_file.read())
|
||||||
|
self.set_model_allowed()
|
||||||
|
self.stdout.write(dumps(self.schema, indent=4))
|
||||||
|
|
||||||
|
def set_model_allowed(self):
|
||||||
|
"""Set model enum"""
|
||||||
|
model_names = []
|
||||||
|
for model in apps.get_models():
|
||||||
|
if not is_model_allowed(model):
|
||||||
|
continue
|
||||||
|
if SerializerModel not in model.__mro__:
|
||||||
|
continue
|
||||||
|
model_names.append(f"{model._meta.app_label}.{model._meta.model_name}")
|
||||||
|
self.schema["properties"]["entries"]["items"]["properties"]["model"]["enum"] = model_names
|
@ -0,0 +1,90 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema",
|
||||||
|
"$id": "http://example.com/example.json",
|
||||||
|
"type": "object",
|
||||||
|
"title": "authentik Blueprint schema",
|
||||||
|
"default": {},
|
||||||
|
"required": [
|
||||||
|
"version",
|
||||||
|
"entries"
|
||||||
|
],
|
||||||
|
"properties": {
|
||||||
|
"version": {
|
||||||
|
"$id": "#/properties/version",
|
||||||
|
"type": "integer",
|
||||||
|
"title": "Blueprint version",
|
||||||
|
"default": 1
|
||||||
|
},
|
||||||
|
"metadata": {
|
||||||
|
"$id": "#/properties/metadata",
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"name"
|
||||||
|
],
|
||||||
|
"properties": {
|
||||||
|
"name": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"labels": {
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"context": {
|
||||||
|
"$id": "#/properties/context",
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": true
|
||||||
|
},
|
||||||
|
"entries": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$id": "#entry",
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"model",
|
||||||
|
"identifiers"
|
||||||
|
],
|
||||||
|
"properties": {
|
||||||
|
"model": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": [
|
||||||
|
"placeholder"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"id": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"attrs": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"name": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Commonly available field, may not exist on all models"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"default": {},
|
||||||
|
"additionalProperties": true
|
||||||
|
},
|
||||||
|
"identifiers": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"pk": {
|
||||||
|
"description": "Commonly available field, may not exist on all models",
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "string",
|
||||||
|
"format": "uuid"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"additionalProperties": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
44
authentik/blueprints/manager.py
Normal file
44
authentik/blueprints/manager.py
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
"""Managed objects manager"""
|
||||||
|
from importlib import import_module
|
||||||
|
from inspect import ismethod
|
||||||
|
|
||||||
|
from django.apps import AppConfig
|
||||||
|
from django.db import DatabaseError, InternalError, ProgrammingError
|
||||||
|
from structlog.stdlib import BoundLogger, get_logger
|
||||||
|
|
||||||
|
LOGGER = get_logger()
|
||||||
|
|
||||||
|
|
||||||
|
class ManagedAppConfig(AppConfig):
|
||||||
|
"""Basic reconciliation logic for apps"""
|
||||||
|
|
||||||
|
_logger: BoundLogger
|
||||||
|
|
||||||
|
def __init__(self, app_name: str, *args, **kwargs) -> None:
|
||||||
|
super().__init__(app_name, *args, **kwargs)
|
||||||
|
self._logger = get_logger().bind(app_name=app_name)
|
||||||
|
|
||||||
|
def ready(self) -> None:
|
||||||
|
self.reconcile()
|
||||||
|
return super().ready()
|
||||||
|
|
||||||
|
def import_module(self, path: str):
|
||||||
|
"""Load module"""
|
||||||
|
import_module(path)
|
||||||
|
|
||||||
|
def reconcile(self) -> None:
|
||||||
|
"""reconcile ourselves"""
|
||||||
|
prefix = "reconcile_"
|
||||||
|
for meth_name in dir(self):
|
||||||
|
meth = getattr(self, meth_name)
|
||||||
|
if not ismethod(meth):
|
||||||
|
continue
|
||||||
|
if not meth_name.startswith(prefix):
|
||||||
|
continue
|
||||||
|
name = meth_name.replace(prefix, "")
|
||||||
|
try:
|
||||||
|
self._logger.debug("Starting reconciler", name=name)
|
||||||
|
meth()
|
||||||
|
self._logger.debug("Successfully reconciled", name=name)
|
||||||
|
except (DatabaseError, ProgrammingError, InternalError) as exc:
|
||||||
|
self._logger.debug("Failed to run reconcile", name=name, exc=exc)
|
135
authentik/blueprints/migrations/0001_initial.py
Normal file
135
authentik/blueprints/migrations/0001_initial.py
Normal file
@ -0,0 +1,135 @@
|
|||||||
|
# Generated by Django 4.0.6 on 2022-07-31 17:35
|
||||||
|
import uuid
|
||||||
|
from glob import glob
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import django.contrib.postgres.fields
|
||||||
|
from dacite import from_dict
|
||||||
|
from django.apps.registry import Apps
|
||||||
|
from django.conf import settings
|
||||||
|
from django.db import migrations, models
|
||||||
|
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
|
||||||
|
from yaml import load
|
||||||
|
|
||||||
|
from authentik.blueprints.v1.labels import LABEL_AUTHENTIK_SYSTEM
|
||||||
|
from authentik.lib.config import CONFIG
|
||||||
|
|
||||||
|
|
||||||
|
def check_blueprint_v1_file(BlueprintInstance: type["BlueprintInstance"], path: Path):
|
||||||
|
"""Check if blueprint should be imported"""
|
||||||
|
from authentik.blueprints.models import BlueprintInstanceStatus
|
||||||
|
from authentik.blueprints.v1.common import BlueprintLoader, BlueprintMetadata
|
||||||
|
from authentik.blueprints.v1.labels import LABEL_AUTHENTIK_INSTANTIATE
|
||||||
|
|
||||||
|
with open(path, "r", encoding="utf-8") as blueprint_file:
|
||||||
|
raw_blueprint = load(blueprint_file.read(), BlueprintLoader)
|
||||||
|
if not raw_blueprint:
|
||||||
|
return
|
||||||
|
metadata = raw_blueprint.get("metadata", None)
|
||||||
|
version = raw_blueprint.get("version", 1)
|
||||||
|
if version != 1:
|
||||||
|
return
|
||||||
|
blueprint_file.seek(0)
|
||||||
|
instance: BlueprintInstance = BlueprintInstance.objects.filter(path=path).first()
|
||||||
|
rel_path = path.relative_to(Path(CONFIG.y("blueprints_dir")))
|
||||||
|
meta = None
|
||||||
|
if metadata:
|
||||||
|
meta = from_dict(BlueprintMetadata, metadata)
|
||||||
|
if meta.labels.get(LABEL_AUTHENTIK_INSTANTIATE, "").lower() == "false":
|
||||||
|
return
|
||||||
|
if not instance:
|
||||||
|
instance = BlueprintInstance(
|
||||||
|
name=meta.name if meta else str(rel_path),
|
||||||
|
path=str(rel_path),
|
||||||
|
context={},
|
||||||
|
status=BlueprintInstanceStatus.UNKNOWN,
|
||||||
|
enabled=True,
|
||||||
|
managed_models=[],
|
||||||
|
last_applied_hash="",
|
||||||
|
metadata=metadata,
|
||||||
|
)
|
||||||
|
instance.save()
|
||||||
|
|
||||||
|
|
||||||
|
def migration_blueprint_import(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
|
||||||
|
BlueprintInstance = apps.get_model("authentik_blueprints", "BlueprintInstance")
|
||||||
|
Flow = apps.get_model("authentik_flows", "Flow")
|
||||||
|
|
||||||
|
db_alias = schema_editor.connection.alias
|
||||||
|
for file in glob(f"{CONFIG.y('blueprints_dir')}/**/*.yaml", recursive=True):
|
||||||
|
check_blueprint_v1_file(BlueprintInstance, Path(file))
|
||||||
|
|
||||||
|
for blueprint in BlueprintInstance.objects.using(db_alias).all():
|
||||||
|
# If we already have flows (and we should always run before flow migrations)
|
||||||
|
# then this is an existing install and we want to disable all blueprints
|
||||||
|
if Flow.objects.using(db_alias).all().exists():
|
||||||
|
blueprint.enabled = False
|
||||||
|
# System blueprints are always enabled
|
||||||
|
if blueprint.metadata.get("labels", {}).get(LABEL_AUTHENTIK_SYSTEM, "").lower() == "true":
|
||||||
|
blueprint.enabled = True
|
||||||
|
blueprint.save()
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
initial = True
|
||||||
|
|
||||||
|
dependencies = [("authentik_flows", "0001_initial")]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name="BlueprintInstance",
|
||||||
|
fields=[
|
||||||
|
("created", models.DateTimeField(auto_now_add=True)),
|
||||||
|
("last_updated", models.DateTimeField(auto_now=True)),
|
||||||
|
(
|
||||||
|
"managed",
|
||||||
|
models.TextField(
|
||||||
|
default=None,
|
||||||
|
help_text="Objects which are managed by authentik. These objects are created and updated automatically. This is flag only indicates that an object can be overwritten by migrations. You can still modify the objects via the API, but expect changes to be overwritten in a later update.",
|
||||||
|
null=True,
|
||||||
|
unique=True,
|
||||||
|
verbose_name="Managed by authentik",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"instance_uuid",
|
||||||
|
models.UUIDField(
|
||||||
|
default=uuid.uuid4, editable=False, primary_key=True, serialize=False
|
||||||
|
),
|
||||||
|
),
|
||||||
|
("name", models.TextField()),
|
||||||
|
("metadata", models.JSONField(default=dict)),
|
||||||
|
("path", models.TextField()),
|
||||||
|
("context", models.JSONField(default=dict)),
|
||||||
|
("last_applied", models.DateTimeField(auto_now=True)),
|
||||||
|
("last_applied_hash", models.TextField()),
|
||||||
|
(
|
||||||
|
"status",
|
||||||
|
models.TextField(
|
||||||
|
choices=[
|
||||||
|
("successful", "Successful"),
|
||||||
|
("warning", "Warning"),
|
||||||
|
("error", "Error"),
|
||||||
|
("orphaned", "Orphaned"),
|
||||||
|
("unknown", "Unknown"),
|
||||||
|
],
|
||||||
|
default="unknown",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
("enabled", models.BooleanField(default=True)),
|
||||||
|
(
|
||||||
|
"managed_models",
|
||||||
|
django.contrib.postgres.fields.ArrayField(
|
||||||
|
base_field=models.TextField(), default=list, size=None
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
"verbose_name": "Blueprint Instance",
|
||||||
|
"verbose_name_plural": "Blueprint Instances",
|
||||||
|
"unique_together": {("name", "path")},
|
||||||
|
},
|
||||||
|
),
|
||||||
|
migrations.RunPython(migration_blueprint_import),
|
||||||
|
]
|
105
authentik/blueprints/models.py
Normal file
105
authentik/blueprints/models.py
Normal file
@ -0,0 +1,105 @@
|
|||||||
|
"""Managed Object models"""
|
||||||
|
from pathlib import Path
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from django.contrib.postgres.fields import ArrayField
|
||||||
|
from django.db import models
|
||||||
|
from django.utils.translation import gettext_lazy as _
|
||||||
|
from requests import RequestException
|
||||||
|
from rest_framework.serializers import Serializer
|
||||||
|
|
||||||
|
from authentik.lib.config import CONFIG
|
||||||
|
from authentik.lib.models import CreatedUpdatedModel, SerializerModel
|
||||||
|
from authentik.lib.sentry import SentryIgnoredException
|
||||||
|
from authentik.lib.utils.http import get_http_session
|
||||||
|
|
||||||
|
|
||||||
|
class BlueprintRetrievalFailed(SentryIgnoredException):
|
||||||
|
"""Error raised when we're unable to fetch the blueprint contents, whether it be HTTP files
|
||||||
|
not being accessible or local files not being readable"""
|
||||||
|
|
||||||
|
|
||||||
|
class ManagedModel(models.Model):
|
||||||
|
"""Model which can be managed by authentik exclusively"""
|
||||||
|
|
||||||
|
managed = models.TextField(
|
||||||
|
default=None,
|
||||||
|
null=True,
|
||||||
|
verbose_name=_("Managed by authentik"),
|
||||||
|
help_text=_(
|
||||||
|
(
|
||||||
|
"Objects which are managed by authentik. These objects are created and updated "
|
||||||
|
"automatically. This is flag only indicates that an object can be overwritten by "
|
||||||
|
"migrations. You can still modify the objects via the API, but expect changes "
|
||||||
|
"to be overwritten in a later update."
|
||||||
|
)
|
||||||
|
),
|
||||||
|
unique=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
|
||||||
|
abstract = True
|
||||||
|
|
||||||
|
|
||||||
|
class BlueprintInstanceStatus(models.TextChoices):
|
||||||
|
"""Instance status"""
|
||||||
|
|
||||||
|
SUCCESSFUL = "successful"
|
||||||
|
WARNING = "warning"
|
||||||
|
ERROR = "error"
|
||||||
|
ORPHANED = "orphaned"
|
||||||
|
UNKNOWN = "unknown"
|
||||||
|
|
||||||
|
|
||||||
|
class BlueprintInstance(SerializerModel, ManagedModel, CreatedUpdatedModel):
|
||||||
|
"""Instance of a single blueprint. Can be parameterized via context attribute when
|
||||||
|
blueprint in `path` has inputs."""
|
||||||
|
|
||||||
|
instance_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
|
||||||
|
|
||||||
|
name = models.TextField()
|
||||||
|
metadata = models.JSONField(default=dict)
|
||||||
|
path = models.TextField()
|
||||||
|
context = models.JSONField(default=dict)
|
||||||
|
last_applied = models.DateTimeField(auto_now=True)
|
||||||
|
last_applied_hash = models.TextField()
|
||||||
|
status = models.TextField(
|
||||||
|
choices=BlueprintInstanceStatus.choices, default=BlueprintInstanceStatus.UNKNOWN
|
||||||
|
)
|
||||||
|
enabled = models.BooleanField(default=True)
|
||||||
|
managed_models = ArrayField(models.TextField(), default=list)
|
||||||
|
|
||||||
|
def retrieve(self) -> str:
|
||||||
|
"""Retrieve blueprint contents"""
|
||||||
|
if urlparse(self.path).scheme != "":
|
||||||
|
try:
|
||||||
|
res = get_http_session().get(self.path, timeout=3, allow_redirects=True)
|
||||||
|
res.raise_for_status()
|
||||||
|
return res.text
|
||||||
|
except RequestException as exc:
|
||||||
|
raise BlueprintRetrievalFailed(exc) from exc
|
||||||
|
path = Path(CONFIG.y("blueprints_dir")).joinpath(Path(self.path))
|
||||||
|
with path.open("r", encoding="utf-8") as _file:
|
||||||
|
return _file.read()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def serializer(self) -> Serializer:
|
||||||
|
from authentik.blueprints.api import BlueprintInstanceSerializer
|
||||||
|
|
||||||
|
return BlueprintInstanceSerializer
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return f"Blueprint Instance {self.name}"
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
|
||||||
|
verbose_name = _("Blueprint Instance")
|
||||||
|
verbose_name_plural = _("Blueprint Instances")
|
||||||
|
unique_together = (
|
||||||
|
(
|
||||||
|
"name",
|
||||||
|
"path",
|
||||||
|
),
|
||||||
|
)
|
12
authentik/blueprints/settings.py
Normal file
12
authentik/blueprints/settings.py
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
"""blueprint Settings"""
|
||||||
|
from celery.schedules import crontab
|
||||||
|
|
||||||
|
from authentik.lib.utils.time import fqdn_rand
|
||||||
|
|
||||||
|
CELERY_BEAT_SCHEDULE = {
|
||||||
|
"blueprints_v1_discover": {
|
||||||
|
"task": "authentik.blueprints.v1.tasks.blueprints_discover",
|
||||||
|
"schedule": crontab(minute=fqdn_rand("blueprints_v1_discover"), hour="*"),
|
||||||
|
"options": {"queue": "authentik_scheduled"},
|
||||||
|
},
|
||||||
|
}
|
48
authentik/blueprints/tests/__init__.py
Normal file
48
authentik/blueprints/tests/__init__.py
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
"""Blueprint helpers"""
|
||||||
|
from functools import wraps
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
from django.apps import apps
|
||||||
|
|
||||||
|
from authentik.blueprints.manager import ManagedAppConfig
|
||||||
|
from authentik.blueprints.models import BlueprintInstance
|
||||||
|
from authentik.lib.config import CONFIG
|
||||||
|
|
||||||
|
|
||||||
|
def apply_blueprint(*files: str):
|
||||||
|
"""Apply blueprint before test"""
|
||||||
|
|
||||||
|
from authentik.blueprints.v1.importer import Importer
|
||||||
|
|
||||||
|
def wrapper_outer(func: Callable):
|
||||||
|
"""Apply blueprint before test"""
|
||||||
|
|
||||||
|
@wraps(func)
|
||||||
|
def wrapper(*args, **kwargs):
|
||||||
|
for file in files:
|
||||||
|
content = BlueprintInstance(path=file).retrieve()
|
||||||
|
Importer(content).apply()
|
||||||
|
return func(*args, **kwargs)
|
||||||
|
|
||||||
|
return wrapper
|
||||||
|
|
||||||
|
return wrapper_outer
|
||||||
|
|
||||||
|
|
||||||
|
def reconcile_app(app_name: str):
|
||||||
|
"""Re-reconcile AppConfig methods"""
|
||||||
|
|
||||||
|
def wrapper_outer(func: Callable):
|
||||||
|
"""Re-reconcile AppConfig methods"""
|
||||||
|
|
||||||
|
@wraps(func)
|
||||||
|
def wrapper(*args, **kwargs):
|
||||||
|
config = apps.get_app_config(app_name)
|
||||||
|
if isinstance(config, ManagedAppConfig):
|
||||||
|
config.reconcile()
|
||||||
|
return func(*args, **kwargs)
|
||||||
|
|
||||||
|
return wrapper
|
||||||
|
|
||||||
|
return wrapper_outer
|
34
authentik/blueprints/tests/test_models.py
Normal file
34
authentik/blueprints/tests/test_models.py
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
"""authentik managed models tests"""
|
||||||
|
from typing import Callable, Type
|
||||||
|
|
||||||
|
from django.apps import apps
|
||||||
|
from django.test import TestCase
|
||||||
|
|
||||||
|
from authentik.blueprints.v1.importer import is_model_allowed
|
||||||
|
from authentik.lib.models import SerializerModel
|
||||||
|
|
||||||
|
|
||||||
|
class TestModels(TestCase):
|
||||||
|
"""Test Models"""
|
||||||
|
|
||||||
|
|
||||||
|
def serializer_tester_factory(test_model: Type[SerializerModel]) -> Callable:
|
||||||
|
"""Test serializer"""
|
||||||
|
|
||||||
|
def tester(self: TestModels):
|
||||||
|
if test_model._meta.abstract:
|
||||||
|
return
|
||||||
|
model_class = test_model()
|
||||||
|
self.assertTrue(isinstance(model_class, SerializerModel))
|
||||||
|
self.assertIsNotNone(model_class.serializer)
|
||||||
|
|
||||||
|
return tester
|
||||||
|
|
||||||
|
|
||||||
|
for app in apps.get_app_configs():
|
||||||
|
if not app.label.startswith("authentik"):
|
||||||
|
continue
|
||||||
|
for model in app.get_models():
|
||||||
|
if not is_model_allowed(model):
|
||||||
|
continue
|
||||||
|
setattr(TestModels, f"test_{app.label}_{model.__name__}", serializer_tester_factory(model))
|
36
authentik/blueprints/tests/test_packaged.py
Normal file
36
authentik/blueprints/tests/test_packaged.py
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
"""test packaged blueprints"""
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
from django.test import TransactionTestCase
|
||||||
|
|
||||||
|
from authentik.blueprints.models import BlueprintInstance
|
||||||
|
from authentik.blueprints.tests import apply_blueprint
|
||||||
|
from authentik.blueprints.v1.importer import Importer
|
||||||
|
from authentik.tenants.models import Tenant
|
||||||
|
|
||||||
|
|
||||||
|
class TestPackaged(TransactionTestCase):
|
||||||
|
"""Empty class, test methods are added dynamically"""
|
||||||
|
|
||||||
|
@apply_blueprint("default/90-default-tenant.yaml")
|
||||||
|
def test_decorator_static(self):
|
||||||
|
"""Test @apply_blueprint decorator"""
|
||||||
|
self.assertTrue(Tenant.objects.filter(domain="authentik-default").exists())
|
||||||
|
|
||||||
|
|
||||||
|
def blueprint_tester(file_name: Path) -> Callable:
|
||||||
|
"""This is used instead of subTest for better visibility"""
|
||||||
|
|
||||||
|
def tester(self: TestPackaged):
|
||||||
|
base = Path("blueprints/")
|
||||||
|
rel_path = Path(file_name).relative_to(base)
|
||||||
|
importer = Importer(BlueprintInstance(path=str(rel_path)).retrieve())
|
||||||
|
self.assertTrue(importer.validate()[0])
|
||||||
|
self.assertTrue(importer.apply())
|
||||||
|
|
||||||
|
return tester
|
||||||
|
|
||||||
|
|
||||||
|
for blueprint_file in Path("blueprints/").glob("**/*.yaml"):
|
||||||
|
setattr(TestPackaged, f"test_blueprint_{blueprint_file}", blueprint_tester(blueprint_file))
|
@ -1,33 +1,56 @@
|
|||||||
"""Test flow transfer"""
|
"""Test blueprints v1"""
|
||||||
from json import dumps
|
|
||||||
|
|
||||||
from django.test import TransactionTestCase
|
from django.test import TransactionTestCase
|
||||||
|
|
||||||
|
from authentik.blueprints.v1.exporter import FlowExporter
|
||||||
|
from authentik.blueprints.v1.importer import Importer, transaction_rollback
|
||||||
from authentik.flows.models import Flow, FlowDesignation, FlowStageBinding
|
from authentik.flows.models import Flow, FlowDesignation, FlowStageBinding
|
||||||
from authentik.flows.transfer.common import DataclassEncoder
|
|
||||||
from authentik.flows.transfer.exporter import FlowExporter
|
|
||||||
from authentik.flows.transfer.importer import FlowImporter, transaction_rollback
|
|
||||||
from authentik.lib.generators import generate_id
|
from authentik.lib.generators import generate_id
|
||||||
from authentik.policies.expression.models import ExpressionPolicy
|
from authentik.policies.expression.models import ExpressionPolicy
|
||||||
from authentik.policies.models import PolicyBinding
|
from authentik.policies.models import PolicyBinding
|
||||||
from authentik.stages.prompt.models import FieldTypes, Prompt, PromptStage
|
from authentik.stages.prompt.models import FieldTypes, Prompt, PromptStage
|
||||||
from authentik.stages.user_login.models import UserLoginStage
|
from authentik.stages.user_login.models import UserLoginStage
|
||||||
|
|
||||||
|
STATIC_PROMPT_EXPORT = """version: 1
|
||||||
|
entries:
|
||||||
|
- identifiers:
|
||||||
|
pk: cb954fd4-65a5-4ad9-b1ee-180ee9559cf4
|
||||||
|
model: authentik_stages_prompt.prompt
|
||||||
|
attrs:
|
||||||
|
field_key: username
|
||||||
|
label: Username
|
||||||
|
type: username
|
||||||
|
required: true
|
||||||
|
placeholder: Username
|
||||||
|
order: 0
|
||||||
|
"""
|
||||||
|
|
||||||
class TestFlowTransfer(TransactionTestCase):
|
YAML_TAG_TESTS = """version: 1
|
||||||
"""Test flow transfer"""
|
context:
|
||||||
|
foo: bar
|
||||||
|
entries:
|
||||||
|
- attrs:
|
||||||
|
expression: return True
|
||||||
|
identifiers:
|
||||||
|
name: !Format [foo-%s-%s, !Context foo, !Context bar]
|
||||||
|
id: default-source-enrollment-if-username
|
||||||
|
model: authentik_policies_expression.expressionpolicy
|
||||||
|
"""
|
||||||
|
|
||||||
def test_bundle_invalid_format(self):
|
|
||||||
"""Test bundle with invalid format"""
|
class TestBlueprintsV1(TransactionTestCase):
|
||||||
importer = FlowImporter('{"version": 3}')
|
"""Test Blueprints"""
|
||||||
self.assertFalse(importer.validate())
|
|
||||||
importer = FlowImporter(
|
def test_blueprint_invalid_format(self):
|
||||||
|
"""Test blueprint with invalid format"""
|
||||||
|
importer = Importer('{"version": 3}')
|
||||||
|
self.assertFalse(importer.validate()[0])
|
||||||
|
importer = Importer(
|
||||||
(
|
(
|
||||||
'{"version": 1,"entries":[{"identifiers":{},"attrs":{},'
|
'{"version": 1,"entries":[{"identifiers":{},"attrs":{},'
|
||||||
'"model": "authentik_core.User"}]}'
|
'"model": "authentik_core.User"}]}'
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
self.assertFalse(importer.validate())
|
self.assertFalse(importer.validate()[0])
|
||||||
|
|
||||||
def test_export_validate_import(self):
|
def test_export_validate_import(self):
|
||||||
"""Test export and validate it"""
|
"""Test export and validate it"""
|
||||||
@ -50,14 +73,38 @@ class TestFlowTransfer(TransactionTestCase):
|
|||||||
exporter = FlowExporter(flow)
|
exporter = FlowExporter(flow)
|
||||||
export = exporter.export()
|
export = exporter.export()
|
||||||
self.assertEqual(len(export.entries), 3)
|
self.assertEqual(len(export.entries), 3)
|
||||||
export_json = exporter.export_to_string()
|
export_yaml = exporter.export_to_string()
|
||||||
|
|
||||||
importer = FlowImporter(export_json)
|
importer = Importer(export_yaml)
|
||||||
self.assertTrue(importer.validate())
|
self.assertTrue(importer.validate()[0])
|
||||||
self.assertTrue(importer.apply())
|
self.assertTrue(importer.apply())
|
||||||
|
|
||||||
self.assertTrue(Flow.objects.filter(slug=flow_slug).exists())
|
self.assertTrue(Flow.objects.filter(slug=flow_slug).exists())
|
||||||
|
|
||||||
|
def test_export_validate_import_re_import(self):
|
||||||
|
"""Test export and import it twice"""
|
||||||
|
count_initial = Prompt.objects.filter(field_key="username").count()
|
||||||
|
|
||||||
|
importer = Importer(STATIC_PROMPT_EXPORT)
|
||||||
|
self.assertTrue(importer.validate()[0])
|
||||||
|
self.assertTrue(importer.apply())
|
||||||
|
|
||||||
|
count_before = Prompt.objects.filter(field_key="username").count()
|
||||||
|
self.assertEqual(count_initial + 1, count_before)
|
||||||
|
|
||||||
|
importer = Importer(STATIC_PROMPT_EXPORT)
|
||||||
|
self.assertTrue(importer.apply())
|
||||||
|
|
||||||
|
self.assertEqual(Prompt.objects.filter(field_key="username").count(), count_before)
|
||||||
|
|
||||||
|
def test_import_yaml_tags(self):
|
||||||
|
"""Test some yaml tags"""
|
||||||
|
ExpressionPolicy.objects.filter(name="foo-foo-bar").delete()
|
||||||
|
importer = Importer(YAML_TAG_TESTS, {"bar": "baz"})
|
||||||
|
self.assertTrue(importer.validate()[0])
|
||||||
|
self.assertTrue(importer.apply())
|
||||||
|
self.assertTrue(ExpressionPolicy.objects.filter(name="foo-foo-bar"))
|
||||||
|
|
||||||
def test_export_validate_import_policies(self):
|
def test_export_validate_import_policies(self):
|
||||||
"""Test export and validate it"""
|
"""Test export and validate it"""
|
||||||
flow_slug = generate_id()
|
flow_slug = generate_id()
|
||||||
@ -80,12 +127,10 @@ class TestFlowTransfer(TransactionTestCase):
|
|||||||
PolicyBinding.objects.create(policy=flow_policy, target=fsb, order=0)
|
PolicyBinding.objects.create(policy=flow_policy, target=fsb, order=0)
|
||||||
|
|
||||||
exporter = FlowExporter(flow)
|
exporter = FlowExporter(flow)
|
||||||
export = exporter.export()
|
export_yaml = exporter.export_to_string()
|
||||||
|
|
||||||
export_json = dumps(export, cls=DataclassEncoder)
|
importer = Importer(export_yaml)
|
||||||
|
self.assertTrue(importer.validate()[0])
|
||||||
importer = FlowImporter(export_json)
|
|
||||||
self.assertTrue(importer.validate())
|
|
||||||
self.assertTrue(importer.apply())
|
self.assertTrue(importer.apply())
|
||||||
self.assertTrue(UserLoginStage.objects.filter(name=stage_name).exists())
|
self.assertTrue(UserLoginStage.objects.filter(name=stage_name).exists())
|
||||||
self.assertTrue(Flow.objects.filter(slug=flow_slug).exists())
|
self.assertTrue(Flow.objects.filter(slug=flow_slug).exists())
|
||||||
@ -125,10 +170,9 @@ class TestFlowTransfer(TransactionTestCase):
|
|||||||
FlowStageBinding.objects.create(target=flow, stage=first_stage, order=0)
|
FlowStageBinding.objects.create(target=flow, stage=first_stage, order=0)
|
||||||
|
|
||||||
exporter = FlowExporter(flow)
|
exporter = FlowExporter(flow)
|
||||||
export = exporter.export()
|
export_yaml = exporter.export_to_string()
|
||||||
export_json = dumps(export, cls=DataclassEncoder)
|
|
||||||
|
|
||||||
importer = FlowImporter(export_json)
|
importer = Importer(export_yaml)
|
||||||
|
|
||||||
self.assertTrue(importer.validate())
|
self.assertTrue(importer.validate()[0])
|
||||||
self.assertTrue(importer.apply())
|
self.assertTrue(importer.apply())
|
45
authentik/blueprints/tests/test_v1_api.py
Normal file
45
authentik/blueprints/tests/test_v1_api.py
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
"""Test blueprints v1 api"""
|
||||||
|
from json import loads
|
||||||
|
from tempfile import NamedTemporaryFile, mkdtemp
|
||||||
|
|
||||||
|
from django.urls import reverse
|
||||||
|
from rest_framework.test import APITestCase
|
||||||
|
from yaml import dump
|
||||||
|
|
||||||
|
from authentik.core.tests.utils import create_test_admin_user
|
||||||
|
from authentik.lib.config import CONFIG
|
||||||
|
|
||||||
|
TMP = mkdtemp("authentik-blueprints")
|
||||||
|
|
||||||
|
|
||||||
|
class TestBlueprintsV1API(APITestCase):
|
||||||
|
"""Test Blueprints API"""
|
||||||
|
|
||||||
|
def setUp(self) -> None:
|
||||||
|
self.user = create_test_admin_user()
|
||||||
|
self.client.force_login(self.user)
|
||||||
|
|
||||||
|
@CONFIG.patch("blueprints_dir", TMP)
|
||||||
|
def test_api_available(self):
|
||||||
|
"""Test valid file"""
|
||||||
|
with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
|
||||||
|
file.write(
|
||||||
|
dump(
|
||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"entries": [],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
file.flush()
|
||||||
|
res = self.client.get(reverse("authentik_api:blueprintinstance-available"))
|
||||||
|
self.assertEqual(res.status_code, 200)
|
||||||
|
response = loads(res.content.decode())
|
||||||
|
self.assertEqual(len(response), 1)
|
||||||
|
self.assertEqual(
|
||||||
|
response[0]["hash"],
|
||||||
|
(
|
||||||
|
"e52bb445b03cd36057258dc9f0ce0fbed8278498ee1470e45315293e5f026d1bd1f9b352"
|
||||||
|
"6871c0003f5c07be5c3316d9d4a08444bd8fed1b3f03294e51e44522"
|
||||||
|
),
|
||||||
|
)
|
148
authentik/blueprints/tests/test_v1_tasks.py
Normal file
148
authentik/blueprints/tests/test_v1_tasks.py
Normal file
@ -0,0 +1,148 @@
|
|||||||
|
"""Test blueprints v1 tasks"""
|
||||||
|
from hashlib import sha512
|
||||||
|
from tempfile import NamedTemporaryFile, mkdtemp
|
||||||
|
|
||||||
|
from django.test import TransactionTestCase
|
||||||
|
from yaml import dump
|
||||||
|
|
||||||
|
from authentik.blueprints.models import BlueprintInstance, BlueprintInstanceStatus
|
||||||
|
from authentik.blueprints.v1.tasks import apply_blueprint, blueprints_discover, blueprints_find
|
||||||
|
from authentik.lib.config import CONFIG
|
||||||
|
from authentik.lib.generators import generate_id
|
||||||
|
|
||||||
|
TMP = mkdtemp("authentik-blueprints")
|
||||||
|
|
||||||
|
|
||||||
|
class TestBlueprintsV1Tasks(TransactionTestCase):
|
||||||
|
"""Test Blueprints v1 Tasks"""
|
||||||
|
|
||||||
|
@CONFIG.patch("blueprints_dir", TMP)
|
||||||
|
def test_invalid_file_syntax(self):
|
||||||
|
"""Test syntactically invalid file"""
|
||||||
|
with NamedTemporaryFile(suffix=".yaml", dir=TMP) as file:
|
||||||
|
file.write(b"{")
|
||||||
|
file.flush()
|
||||||
|
blueprints = blueprints_find()
|
||||||
|
self.assertEqual(blueprints, [])
|
||||||
|
|
||||||
|
@CONFIG.patch("blueprints_dir", TMP)
|
||||||
|
def test_invalid_file_version(self):
|
||||||
|
"""Test invalid file"""
|
||||||
|
with NamedTemporaryFile(suffix=".yaml", dir=TMP) as file:
|
||||||
|
file.write(b"version: 2")
|
||||||
|
file.flush()
|
||||||
|
blueprints = blueprints_find()
|
||||||
|
self.assertEqual(blueprints, [])
|
||||||
|
|
||||||
|
@CONFIG.patch("blueprints_dir", TMP)
|
||||||
|
def test_valid(self):
|
||||||
|
"""Test valid file"""
|
||||||
|
blueprint_id = generate_id()
|
||||||
|
with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
|
||||||
|
file.write(
|
||||||
|
dump(
|
||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"entries": [],
|
||||||
|
"metadata": {
|
||||||
|
"name": blueprint_id,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
file.seek(0)
|
||||||
|
file_hash = sha512(file.read().encode()).hexdigest()
|
||||||
|
file.flush()
|
||||||
|
blueprints_discover() # pylint: disable=no-value-for-parameter
|
||||||
|
instance = BlueprintInstance.objects.filter(name=blueprint_id).first()
|
||||||
|
self.assertEqual(instance.last_applied_hash, file_hash)
|
||||||
|
self.assertEqual(
|
||||||
|
instance.metadata,
|
||||||
|
{
|
||||||
|
"name": blueprint_id,
|
||||||
|
"labels": {},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
@CONFIG.patch("blueprints_dir", TMP)
|
||||||
|
def test_valid_updated(self):
|
||||||
|
"""Test valid file"""
|
||||||
|
with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
|
||||||
|
file.write(
|
||||||
|
dump(
|
||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"entries": [],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
file.flush()
|
||||||
|
blueprints_discover() # pylint: disable=no-value-for-parameter
|
||||||
|
self.assertEqual(
|
||||||
|
BlueprintInstance.objects.first().last_applied_hash,
|
||||||
|
(
|
||||||
|
"e52bb445b03cd36057258dc9f0ce0fbed8278498ee1470e45315293e5f026d1b"
|
||||||
|
"d1f9b3526871c0003f5c07be5c3316d9d4a08444bd8fed1b3f03294e51e44522"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
self.assertEqual(BlueprintInstance.objects.first().metadata, {})
|
||||||
|
file.write(
|
||||||
|
dump(
|
||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"entries": [],
|
||||||
|
"metadata": {
|
||||||
|
"name": "foo",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
file.flush()
|
||||||
|
blueprints_discover() # pylint: disable=no-value-for-parameter
|
||||||
|
self.assertEqual(
|
||||||
|
BlueprintInstance.objects.first().last_applied_hash,
|
||||||
|
(
|
||||||
|
"fc62fea96067da8592bdf90927246d0ca150b045447df93b0652a0e20a8bc327"
|
||||||
|
"681510b5db37ea98759c61f9a98dd2381f46a3b5a2da69dfb45158897f14e824"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
BlueprintInstance.objects.first().metadata,
|
||||||
|
{
|
||||||
|
"name": "foo",
|
||||||
|
"labels": {},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
@CONFIG.patch("blueprints_dir", TMP)
|
||||||
|
def test_valid_disabled(self):
|
||||||
|
"""Test valid file"""
|
||||||
|
with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
|
||||||
|
file.write(
|
||||||
|
dump(
|
||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"entries": [],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
file.flush()
|
||||||
|
instance: BlueprintInstance = BlueprintInstance.objects.create(
|
||||||
|
name=generate_id(),
|
||||||
|
path=file.name,
|
||||||
|
enabled=False,
|
||||||
|
status=BlueprintInstanceStatus.UNKNOWN,
|
||||||
|
)
|
||||||
|
instance.refresh_from_db()
|
||||||
|
self.assertEqual(instance.last_applied_hash, "")
|
||||||
|
self.assertEqual(
|
||||||
|
instance.status,
|
||||||
|
BlueprintInstanceStatus.UNKNOWN,
|
||||||
|
)
|
||||||
|
apply_blueprint(instance.pk) # pylint: disable=no-value-for-parameter
|
||||||
|
instance.refresh_from_db()
|
||||||
|
self.assertEqual(instance.last_applied_hash, "")
|
||||||
|
self.assertEqual(
|
||||||
|
instance.status,
|
||||||
|
BlueprintInstanceStatus.UNKNOWN,
|
||||||
|
)
|
0
authentik/blueprints/v1/__init__.py
Normal file
0
authentik/blueprints/v1/__init__.py
Normal file
255
authentik/blueprints/v1/common.py
Normal file
255
authentik/blueprints/v1/common.py
Normal file
@ -0,0 +1,255 @@
|
|||||||
|
"""transfer common classes"""
|
||||||
|
from collections import OrderedDict
|
||||||
|
from dataclasses import asdict, dataclass, field, is_dataclass
|
||||||
|
from enum import Enum
|
||||||
|
from typing import Any, Optional
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from django.apps import apps
|
||||||
|
from django.db.models import Model, Q
|
||||||
|
from rest_framework.fields import Field
|
||||||
|
from rest_framework.serializers import Serializer
|
||||||
|
from yaml import SafeDumper, SafeLoader, ScalarNode, SequenceNode
|
||||||
|
|
||||||
|
from authentik.lib.models import SerializerModel
|
||||||
|
from authentik.lib.sentry import SentryIgnoredException
|
||||||
|
from authentik.policies.models import PolicyBindingModel
|
||||||
|
|
||||||
|
|
||||||
|
def get_attrs(obj: SerializerModel) -> dict[str, Any]:
|
||||||
|
"""Get object's attributes via their serializer, and convert it to a normal dict"""
|
||||||
|
serializer: Serializer = obj.serializer(obj)
|
||||||
|
data = dict(serializer.data)
|
||||||
|
|
||||||
|
for field_name, _field in serializer.fields.items():
|
||||||
|
_field: Field
|
||||||
|
if field_name not in data:
|
||||||
|
continue
|
||||||
|
if _field.read_only:
|
||||||
|
data.pop(field_name, None)
|
||||||
|
if _field.get_initial() == data.get(field_name, None):
|
||||||
|
data.pop(field_name, None)
|
||||||
|
if field_name.endswith("_set"):
|
||||||
|
data.pop(field_name, None)
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class BlueprintEntryState:
|
||||||
|
"""State of a single instance"""
|
||||||
|
|
||||||
|
instance: Optional[Model] = None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class BlueprintEntry:
|
||||||
|
"""Single entry of a blueprint"""
|
||||||
|
|
||||||
|
identifiers: dict[str, Any]
|
||||||
|
model: str
|
||||||
|
attrs: Optional[dict[str, Any]] = field(default_factory=dict)
|
||||||
|
|
||||||
|
# pylint: disable=invalid-name
|
||||||
|
id: Optional[str] = None
|
||||||
|
|
||||||
|
_state: BlueprintEntryState = field(default_factory=BlueprintEntryState)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def from_model(model: SerializerModel, *extra_identifier_names: str) -> "BlueprintEntry":
|
||||||
|
"""Convert a SerializerModel instance to a blueprint Entry"""
|
||||||
|
identifiers = {
|
||||||
|
"pk": model.pk,
|
||||||
|
}
|
||||||
|
all_attrs = get_attrs(model)
|
||||||
|
|
||||||
|
for extra_identifier_name in extra_identifier_names:
|
||||||
|
identifiers[extra_identifier_name] = all_attrs.pop(extra_identifier_name)
|
||||||
|
return BlueprintEntry(
|
||||||
|
identifiers=identifiers,
|
||||||
|
model=f"{model._meta.app_label}.{model._meta.model_name}",
|
||||||
|
attrs=all_attrs,
|
||||||
|
)
|
||||||
|
|
||||||
|
def tag_resolver(self, value: Any, blueprint: "Blueprint") -> Any:
|
||||||
|
"""Check if we have any special tags that need handling"""
|
||||||
|
if isinstance(value, YAMLTag):
|
||||||
|
return value.resolve(self, blueprint)
|
||||||
|
if isinstance(value, dict):
|
||||||
|
for key, inner_value in value.items():
|
||||||
|
value[key] = self.tag_resolver(inner_value, blueprint)
|
||||||
|
if isinstance(value, list):
|
||||||
|
for idx, inner_value in enumerate(value):
|
||||||
|
value[idx] = self.tag_resolver(inner_value, blueprint)
|
||||||
|
return value
|
||||||
|
|
||||||
|
def get_attrs(self, blueprint: "Blueprint") -> dict[str, Any]:
|
||||||
|
"""Get attributes of this entry, with all yaml tags resolved"""
|
||||||
|
return self.tag_resolver(self.attrs, blueprint)
|
||||||
|
|
||||||
|
def get_identifiers(self, blueprint: "Blueprint") -> dict[str, Any]:
|
||||||
|
"""Get attributes of this entry, with all yaml tags resolved"""
|
||||||
|
return self.tag_resolver(self.identifiers, blueprint)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class BlueprintMetadata:
|
||||||
|
"""Optional blueprint metadata"""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
labels: dict[str, str] = field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Blueprint:
|
||||||
|
"""Dataclass used for a full export"""
|
||||||
|
|
||||||
|
version: int = field(default=1)
|
||||||
|
entries: list[BlueprintEntry] = field(default_factory=list)
|
||||||
|
|
||||||
|
metadata: Optional[BlueprintMetadata] = field(default=None)
|
||||||
|
context: Optional[dict] = field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
class YAMLTag:
|
||||||
|
"""Base class for all YAML Tags"""
|
||||||
|
|
||||||
|
def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any:
|
||||||
|
"""Implement yaml tag logic"""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
|
||||||
|
class KeyOf(YAMLTag):
|
||||||
|
"""Reference another object by their ID"""
|
||||||
|
|
||||||
|
id_from: str
|
||||||
|
|
||||||
|
# pylint: disable=unused-argument
|
||||||
|
def __init__(self, loader: "BlueprintLoader", node: ScalarNode) -> None:
|
||||||
|
super().__init__()
|
||||||
|
self.id_from = node.value
|
||||||
|
|
||||||
|
def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any:
|
||||||
|
for _entry in blueprint.entries:
|
||||||
|
if _entry.id == self.id_from and _entry._state.instance:
|
||||||
|
# Special handling for PolicyBindingModels, as they'll have a different PK
|
||||||
|
# which is used when creating policy bindings
|
||||||
|
if (
|
||||||
|
isinstance(_entry._state.instance, PolicyBindingModel)
|
||||||
|
and entry.model.lower() == "authentik_policies.policybinding"
|
||||||
|
):
|
||||||
|
return _entry._state.instance.pbm_uuid
|
||||||
|
return _entry._state.instance.pk
|
||||||
|
raise ValueError(
|
||||||
|
f"KeyOf: failed to find entry with `id` of `{self.id_from}` and a model instance"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Context(YAMLTag):
|
||||||
|
"""Lookup key from instance context"""
|
||||||
|
|
||||||
|
key: str
|
||||||
|
default: Optional[Any]
|
||||||
|
|
||||||
|
# pylint: disable=unused-argument
|
||||||
|
def __init__(self, loader: "BlueprintLoader", node: ScalarNode | SequenceNode) -> None:
|
||||||
|
super().__init__()
|
||||||
|
self.default = None
|
||||||
|
if isinstance(node, ScalarNode):
|
||||||
|
self.key = node.value
|
||||||
|
if isinstance(node, SequenceNode):
|
||||||
|
self.key = node.value[0].value
|
||||||
|
self.default = node.value[1].value
|
||||||
|
|
||||||
|
def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any:
|
||||||
|
value = self.default
|
||||||
|
if self.key in blueprint.context:
|
||||||
|
value = blueprint.context[self.key]
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
class Format(YAMLTag):
|
||||||
|
"""Format a string"""
|
||||||
|
|
||||||
|
format_string: str
|
||||||
|
args: list[Any]
|
||||||
|
|
||||||
|
# pylint: disable=unused-argument
|
||||||
|
def __init__(self, loader: "BlueprintLoader", node: SequenceNode) -> None:
|
||||||
|
super().__init__()
|
||||||
|
self.format_string = node.value[0].value
|
||||||
|
self.args = []
|
||||||
|
for raw_node in node.value[1:]:
|
||||||
|
self.args.append(raw_node.value)
|
||||||
|
|
||||||
|
def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any:
|
||||||
|
try:
|
||||||
|
return self.format_string % tuple(self.args)
|
||||||
|
except TypeError as exc:
|
||||||
|
raise EntryInvalidError(exc)
|
||||||
|
|
||||||
|
|
||||||
|
class Find(YAMLTag):
|
||||||
|
"""Find any object"""
|
||||||
|
|
||||||
|
model_name: str
|
||||||
|
conditions: list[list]
|
||||||
|
|
||||||
|
model_class: type[Model]
|
||||||
|
|
||||||
|
def __init__(self, loader: "BlueprintLoader", node: SequenceNode) -> None:
|
||||||
|
super().__init__()
|
||||||
|
self.model_name = node.value[0].value
|
||||||
|
self.model_class = apps.get_model(*self.model_name.split("."))
|
||||||
|
self.conditions = []
|
||||||
|
for raw_node in node.value[1:]:
|
||||||
|
values = []
|
||||||
|
for node_values in raw_node.value:
|
||||||
|
values.append(loader.construct_object(node_values))
|
||||||
|
self.conditions.append(values)
|
||||||
|
|
||||||
|
def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any:
|
||||||
|
query = Q()
|
||||||
|
for cond in self.conditions:
|
||||||
|
query &= Q(**{cond[0]: cond[1]})
|
||||||
|
instance = self.model_class.objects.filter(query).first()
|
||||||
|
if instance:
|
||||||
|
return instance.pk
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class BlueprintDumper(SafeDumper):
|
||||||
|
"""Dump dataclasses to yaml"""
|
||||||
|
|
||||||
|
default_flow_style = False
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
self.add_representer(UUID, lambda self, data: self.represent_str(str(data)))
|
||||||
|
self.add_representer(OrderedDict, lambda self, data: self.represent_dict(dict(data)))
|
||||||
|
self.add_representer(Enum, lambda self, data: self.represent_str(data.value))
|
||||||
|
|
||||||
|
def represent(self, data) -> None:
|
||||||
|
if is_dataclass(data):
|
||||||
|
|
||||||
|
def factory(items):
|
||||||
|
final_dict = dict(items)
|
||||||
|
final_dict.pop("_state", None)
|
||||||
|
return final_dict
|
||||||
|
|
||||||
|
data = asdict(data, dict_factory=factory)
|
||||||
|
return super().represent(data)
|
||||||
|
|
||||||
|
|
||||||
|
class BlueprintLoader(SafeLoader):
|
||||||
|
"""Loader for blueprints with custom tag support"""
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
self.add_constructor("!KeyOf", KeyOf)
|
||||||
|
self.add_constructor("!Find", Find)
|
||||||
|
self.add_constructor("!Context", Context)
|
||||||
|
self.add_constructor("!Format", Format)
|
||||||
|
|
||||||
|
|
||||||
|
class EntryInvalidError(SentryIgnoredException):
|
||||||
|
"""Error raised when an entry is invalid"""
|
140
authentik/blueprints/v1/exporter.py
Normal file
140
authentik/blueprints/v1/exporter.py
Normal file
@ -0,0 +1,140 @@
|
|||||||
|
"""Blueprint exporter"""
|
||||||
|
from typing import Iterator
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from django.apps import apps
|
||||||
|
from django.db.models import Q
|
||||||
|
from django.utils.timezone import now
|
||||||
|
from django.utils.translation import gettext as _
|
||||||
|
from yaml import dump
|
||||||
|
|
||||||
|
from authentik.blueprints.v1.common import (
|
||||||
|
Blueprint,
|
||||||
|
BlueprintDumper,
|
||||||
|
BlueprintEntry,
|
||||||
|
BlueprintMetadata,
|
||||||
|
)
|
||||||
|
from authentik.blueprints.v1.importer import is_model_allowed
|
||||||
|
from authentik.blueprints.v1.labels import LABEL_AUTHENTIK_GENERATED
|
||||||
|
from authentik.flows.models import Flow, FlowStageBinding, Stage
|
||||||
|
from authentik.lib.models import SerializerModel
|
||||||
|
from authentik.policies.models import Policy, PolicyBinding
|
||||||
|
from authentik.stages.prompt.models import PromptStage
|
||||||
|
|
||||||
|
|
||||||
|
class Exporter:
|
||||||
|
"""Export flow with attached stages into yaml"""
|
||||||
|
|
||||||
|
excluded_models = []
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.excluded_models = []
|
||||||
|
|
||||||
|
def get_entries(self) -> Iterator[BlueprintEntry]:
|
||||||
|
"""Get blueprint entries"""
|
||||||
|
for model in apps.get_models():
|
||||||
|
if not is_model_allowed(model):
|
||||||
|
continue
|
||||||
|
if model in self.excluded_models:
|
||||||
|
continue
|
||||||
|
if SerializerModel not in model.__mro__:
|
||||||
|
continue
|
||||||
|
for obj in model.objects.all():
|
||||||
|
yield BlueprintEntry.from_model(obj)
|
||||||
|
|
||||||
|
def _pre_export(self, blueprint: Blueprint):
|
||||||
|
"""Hook to run anything pre-export"""
|
||||||
|
|
||||||
|
def export(self) -> Blueprint:
|
||||||
|
"""Create a list of all objects and create a blueprint"""
|
||||||
|
blueprint = Blueprint()
|
||||||
|
self._pre_export(blueprint)
|
||||||
|
blueprint.metadata = BlueprintMetadata(
|
||||||
|
name=_("authentik Export - %(date)s" % {"date": str(now())}),
|
||||||
|
labels={
|
||||||
|
LABEL_AUTHENTIK_GENERATED: "true",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
blueprint.entries = list(self.get_entries())
|
||||||
|
return blueprint
|
||||||
|
|
||||||
|
def export_to_string(self) -> str:
|
||||||
|
"""Call export and convert it to yaml"""
|
||||||
|
blueprint = self.export()
|
||||||
|
return dump(blueprint, Dumper=BlueprintDumper)
|
||||||
|
|
||||||
|
|
||||||
|
class FlowExporter(Exporter):
|
||||||
|
"""Exporter customised to only return objects related to `flow`"""
|
||||||
|
|
||||||
|
flow: Flow
|
||||||
|
with_policies: bool
|
||||||
|
with_stage_prompts: bool
|
||||||
|
|
||||||
|
pbm_uuids: list[UUID]
|
||||||
|
|
||||||
|
def __init__(self, flow: Flow):
|
||||||
|
super().__init__()
|
||||||
|
self.flow = flow
|
||||||
|
self.with_policies = True
|
||||||
|
self.with_stage_prompts = True
|
||||||
|
|
||||||
|
def _pre_export(self, blueprint: Blueprint):
|
||||||
|
if not self.with_policies:
|
||||||
|
return
|
||||||
|
self.pbm_uuids = [self.flow.pbm_uuid]
|
||||||
|
self.pbm_uuids += FlowStageBinding.objects.filter(target=self.flow).values_list(
|
||||||
|
"pbm_uuid", flat=True
|
||||||
|
)
|
||||||
|
|
||||||
|
def walk_stages(self) -> Iterator[BlueprintEntry]:
|
||||||
|
"""Convert all stages attached to self.flow into BlueprintEntry objects"""
|
||||||
|
stages = Stage.objects.filter(flow=self.flow).select_related().select_subclasses()
|
||||||
|
for stage in stages:
|
||||||
|
if isinstance(stage, PromptStage):
|
||||||
|
pass
|
||||||
|
yield BlueprintEntry.from_model(stage, "name")
|
||||||
|
|
||||||
|
def walk_stage_bindings(self) -> Iterator[BlueprintEntry]:
|
||||||
|
"""Convert all bindings attached to self.flow into BlueprintEntry objects"""
|
||||||
|
bindings = FlowStageBinding.objects.filter(target=self.flow).select_related()
|
||||||
|
for binding in bindings:
|
||||||
|
yield BlueprintEntry.from_model(binding, "target", "stage", "order")
|
||||||
|
|
||||||
|
def walk_policies(self) -> Iterator[BlueprintEntry]:
|
||||||
|
"""Walk over all policies. This is done at the beginning of the export for stages that have
|
||||||
|
a direct foreign key to a policy."""
|
||||||
|
# Special case for PromptStage as that has a direct M2M to policy, we have to ensure
|
||||||
|
# all policies referenced in there we also include here
|
||||||
|
prompt_stages = PromptStage.objects.filter(flow=self.flow).values_list("pk", flat=True)
|
||||||
|
query = Q(bindings__in=self.pbm_uuids) | Q(promptstage__in=prompt_stages)
|
||||||
|
policies = Policy.objects.filter(query).select_related()
|
||||||
|
for policy in policies:
|
||||||
|
yield BlueprintEntry.from_model(policy)
|
||||||
|
|
||||||
|
def walk_policy_bindings(self) -> Iterator[BlueprintEntry]:
|
||||||
|
"""Walk over all policybindings relative to us. This is run at the end of the export, as
|
||||||
|
we are sure all objects exist now."""
|
||||||
|
bindings = PolicyBinding.objects.filter(target__in=self.pbm_uuids).select_related()
|
||||||
|
for binding in bindings:
|
||||||
|
yield BlueprintEntry.from_model(binding, "policy", "target", "order")
|
||||||
|
|
||||||
|
def walk_stage_prompts(self) -> Iterator[BlueprintEntry]:
|
||||||
|
"""Walk over all prompts associated with any PromptStages"""
|
||||||
|
prompt_stages = PromptStage.objects.filter(flow=self.flow)
|
||||||
|
for stage in prompt_stages:
|
||||||
|
for prompt in stage.fields.all():
|
||||||
|
yield BlueprintEntry.from_model(prompt)
|
||||||
|
|
||||||
|
def get_entries(self) -> Iterator[BlueprintEntry]:
|
||||||
|
entries = []
|
||||||
|
entries.append(BlueprintEntry.from_model(self.flow, "slug"))
|
||||||
|
if self.with_stage_prompts:
|
||||||
|
entries.extend(self.walk_stage_prompts())
|
||||||
|
if self.with_policies:
|
||||||
|
entries.extend(self.walk_policies())
|
||||||
|
entries.extend(self.walk_stages())
|
||||||
|
entries.extend(self.walk_stage_bindings())
|
||||||
|
if self.with_policies:
|
||||||
|
entries.extend(self.walk_policy_bindings())
|
||||||
|
return entries
|
@ -1,11 +1,11 @@
|
|||||||
"""Flow importer"""
|
"""Blueprint importer"""
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
from json import loads
|
from typing import Any, Optional
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
from dacite import from_dict
|
from dacite import from_dict
|
||||||
from dacite.exceptions import DaciteError
|
from dacite.exceptions import DaciteError
|
||||||
|
from deepmerge import always_merger
|
||||||
from django.apps import apps
|
from django.apps import apps
|
||||||
from django.db import transaction
|
from django.db import transaction
|
||||||
from django.db.models import Model
|
from django.db.models import Model
|
||||||
@ -14,38 +14,87 @@ from django.db.utils import IntegrityError
|
|||||||
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 authentik.flows.models import Flow, FlowStageBinding, Stage
|
from authentik.blueprints.v1.common import (
|
||||||
from authentik.flows.transfer.common import EntryInvalidError, FlowBundle, FlowBundleEntry
|
Blueprint,
|
||||||
|
BlueprintEntry,
|
||||||
|
BlueprintEntryState,
|
||||||
|
BlueprintLoader,
|
||||||
|
EntryInvalidError,
|
||||||
|
)
|
||||||
|
from authentik.core.models import (
|
||||||
|
AuthenticatedSession,
|
||||||
|
PropertyMapping,
|
||||||
|
Provider,
|
||||||
|
Source,
|
||||||
|
UserSourceConnection,
|
||||||
|
)
|
||||||
|
from authentik.flows.models import Stage
|
||||||
from authentik.lib.models import SerializerModel
|
from authentik.lib.models import SerializerModel
|
||||||
from authentik.policies.models import Policy, PolicyBinding
|
from authentik.outposts.models import OutpostServiceConnection
|
||||||
from authentik.stages.prompt.models import Prompt
|
from authentik.policies.models import Policy, PolicyBindingModel
|
||||||
|
|
||||||
ALLOWED_MODELS = (Flow, FlowStageBinding, Stage, Policy, PolicyBinding, Prompt)
|
|
||||||
|
def is_model_allowed(model: type[Model]) -> bool:
|
||||||
|
"""Check if model is allowed"""
|
||||||
|
# pylint: disable=imported-auth-user
|
||||||
|
from django.contrib.auth.models import Group as DjangoGroup
|
||||||
|
from django.contrib.auth.models import User as DjangoUser
|
||||||
|
|
||||||
|
excluded_models = (
|
||||||
|
DjangoUser,
|
||||||
|
DjangoGroup,
|
||||||
|
# Base classes
|
||||||
|
Provider,
|
||||||
|
Source,
|
||||||
|
PropertyMapping,
|
||||||
|
UserSourceConnection,
|
||||||
|
Stage,
|
||||||
|
OutpostServiceConnection,
|
||||||
|
Policy,
|
||||||
|
PolicyBindingModel,
|
||||||
|
# Classes that have other dependencies
|
||||||
|
AuthenticatedSession,
|
||||||
|
)
|
||||||
|
return model not in excluded_models
|
||||||
|
|
||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
def transaction_rollback():
|
def transaction_rollback():
|
||||||
"""Enters an atomic transaction and always triggers a rollback at the end of the block."""
|
"""Enters an atomic transaction and always triggers a rollback at the end of the block."""
|
||||||
atomic = transaction.atomic()
|
atomic = transaction.atomic()
|
||||||
|
# pylint: disable=unnecessary-dunder-call
|
||||||
atomic.__enter__()
|
atomic.__enter__()
|
||||||
yield
|
yield
|
||||||
atomic.__exit__(IntegrityError, None, None)
|
atomic.__exit__(IntegrityError, None, None)
|
||||||
|
|
||||||
|
|
||||||
class FlowImporter:
|
class Importer:
|
||||||
"""Import Flow from json"""
|
"""Import Blueprint from YAML"""
|
||||||
|
|
||||||
logger: BoundLogger
|
logger: BoundLogger
|
||||||
|
|
||||||
def __init__(self, json_input: str):
|
def __init__(self, yaml_input: str, context: Optional[dict] = None):
|
||||||
self.__pk_map: dict[Any, Model] = {}
|
self.__pk_map: dict[Any, Model] = {}
|
||||||
self.logger = get_logger()
|
self.logger = get_logger()
|
||||||
import_dict = loads(json_input)
|
import_dict = load(yaml_input, BlueprintLoader)
|
||||||
try:
|
try:
|
||||||
self.__import = from_dict(FlowBundle, import_dict)
|
self.__import = from_dict(Blueprint, import_dict)
|
||||||
except DaciteError as exc:
|
except DaciteError as exc:
|
||||||
raise EntryInvalidError from exc
|
raise EntryInvalidError from exc
|
||||||
|
context = {}
|
||||||
|
always_merger.merge(context, self.__import.context)
|
||||||
|
if context:
|
||||||
|
always_merger.merge(context, context)
|
||||||
|
self.__import.context = context
|
||||||
|
|
||||||
|
@property
|
||||||
|
def blueprint(self) -> Blueprint:
|
||||||
|
"""Get imported blueprint"""
|
||||||
|
return self.__import
|
||||||
|
|
||||||
def __update_pks_for_attrs(self, attrs: dict[str, Any]) -> dict[str, Any]:
|
def __update_pks_for_attrs(self, attrs: dict[str, Any]) -> dict[str, Any]:
|
||||||
"""Replace any value if it is a known primary key of an other object"""
|
"""Replace any value if it is a known primary key of an other object"""
|
||||||
@ -74,7 +123,9 @@ class FlowImporter:
|
|||||||
"""Generate an or'd query from all identifiers in an entry"""
|
"""Generate an or'd query from all identifiers in an entry"""
|
||||||
# Since identifiers can also be pk-references to other objects (see FlowStageBinding)
|
# Since identifiers can also be pk-references to other objects (see FlowStageBinding)
|
||||||
# we have to ensure those references are also replaced
|
# we have to ensure those references are also replaced
|
||||||
main_query = Q(pk=attrs["pk"])
|
main_query = Q()
|
||||||
|
if "pk" in attrs:
|
||||||
|
main_query = Q(pk=attrs["pk"])
|
||||||
sub_query = Q()
|
sub_query = Q()
|
||||||
for identifier, value in attrs.items():
|
for identifier, value in attrs.items():
|
||||||
if isinstance(value, dict):
|
if isinstance(value, dict):
|
||||||
@ -84,19 +135,22 @@ class FlowImporter:
|
|||||||
sub_query &= Q(**{identifier: value})
|
sub_query &= Q(**{identifier: value})
|
||||||
return main_query | sub_query
|
return main_query | sub_query
|
||||||
|
|
||||||
def _validate_single(self, entry: FlowBundleEntry) -> BaseSerializer:
|
def _validate_single(self, entry: BlueprintEntry) -> BaseSerializer:
|
||||||
"""Validate a single entry"""
|
"""Validate a single entry"""
|
||||||
model_app_label, model_name = entry.model.split(".")
|
model_app_label, model_name = entry.model.split(".")
|
||||||
model: type[SerializerModel] = apps.get_model(model_app_label, model_name)
|
model: type[SerializerModel] = apps.get_model(model_app_label, model_name)
|
||||||
if not isinstance(model(), ALLOWED_MODELS):
|
# Don't use isinstance since we don't want to check for inheritance
|
||||||
|
if not is_model_allowed(model):
|
||||||
raise EntryInvalidError(f"Model {model} not allowed")
|
raise EntryInvalidError(f"Model {model} not allowed")
|
||||||
|
if entry.identifiers == {}:
|
||||||
|
raise EntryInvalidError("No identifiers")
|
||||||
|
|
||||||
# If we try to validate without referencing a possible instance
|
# If we try to validate without referencing a possible instance
|
||||||
# we'll get a duplicate error, hence we load the model here and return
|
# we'll get a duplicate error, hence we load the model here and return
|
||||||
# the full serializer for later usage
|
# the full serializer for later usage
|
||||||
# Because a model might have multiple unique columns, we chain all identifiers together
|
# Because a model might have multiple unique columns, we chain all identifiers together
|
||||||
# to create an OR query.
|
# to create an OR query.
|
||||||
updated_identifiers = self.__update_pks_for_attrs(entry.identifiers)
|
updated_identifiers = self.__update_pks_for_attrs(entry.get_identifiers(self.__import))
|
||||||
for key, value in list(updated_identifiers.items()):
|
for key, value in list(updated_identifiers.items()):
|
||||||
if isinstance(value, dict) and "pk" in value:
|
if isinstance(value, dict) and "pk" in value:
|
||||||
del updated_identifiers[key]
|
del updated_identifiers[key]
|
||||||
@ -113,9 +167,15 @@ class FlowImporter:
|
|||||||
pk=model_instance.pk,
|
pk=model_instance.pk,
|
||||||
)
|
)
|
||||||
serializer_kwargs["instance"] = model_instance
|
serializer_kwargs["instance"] = model_instance
|
||||||
|
serializer_kwargs["partial"] = True
|
||||||
else:
|
else:
|
||||||
self.logger.debug("initialise new instance", model=model, **updated_identifiers)
|
self.logger.debug("initialise new instance", model=model, **updated_identifiers)
|
||||||
full_data = self.__update_pks_for_attrs(entry.attrs)
|
model_instance = model()
|
||||||
|
# pk needs to be set on the model instance otherwise a new one will be generated
|
||||||
|
if "pk" in updated_identifiers:
|
||||||
|
model_instance.pk = updated_identifiers["pk"]
|
||||||
|
serializer_kwargs["instance"] = model_instance
|
||||||
|
full_data = self.__update_pks_for_attrs(entry.get_attrs(self.__import))
|
||||||
full_data.update(updated_identifiers)
|
full_data.update(updated_identifiers)
|
||||||
serializer_kwargs["data"] = full_data
|
serializer_kwargs["data"] = full_data
|
||||||
|
|
||||||
@ -127,7 +187,7 @@ class FlowImporter:
|
|||||||
return serializer
|
return serializer
|
||||||
|
|
||||||
def apply(self) -> bool:
|
def apply(self) -> bool:
|
||||||
"""Apply (create/update) flow json, in database transaction"""
|
"""Apply (create/update) models yaml, in database transaction"""
|
||||||
try:
|
try:
|
||||||
with transaction.atomic():
|
with transaction.atomic():
|
||||||
if not self._apply_models():
|
if not self._apply_models():
|
||||||
@ -140,10 +200,9 @@ class FlowImporter:
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
def _apply_models(self) -> bool:
|
def _apply_models(self) -> bool:
|
||||||
"""Apply (create/update) flow json"""
|
"""Apply (create/update) models yaml"""
|
||||||
self.__pk_map = {}
|
self.__pk_map = {}
|
||||||
entries = deepcopy(self.__import.entries)
|
for entry in self.__import.entries:
|
||||||
for entry in entries:
|
|
||||||
model_app_label, model_name = entry.model.split(".")
|
model_app_label, model_name = entry.model.split(".")
|
||||||
try:
|
try:
|
||||||
model: SerializerModel = apps.get_model(model_app_label, model_name)
|
model: SerializerModel = apps.get_model(model_app_label, model_name)
|
||||||
@ -156,23 +215,32 @@ class FlowImporter:
|
|||||||
try:
|
try:
|
||||||
serializer = self._validate_single(entry)
|
serializer = self._validate_single(entry)
|
||||||
except EntryInvalidError as exc:
|
except EntryInvalidError as exc:
|
||||||
self.logger.warning("entry not valid", entry=entry, error=exc)
|
self.logger.warning("entry invalid", entry=entry, error=exc)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
model = serializer.save()
|
model = serializer.save()
|
||||||
self.__pk_map[entry.identifiers["pk"]] = model.pk
|
if "pk" in entry.identifiers:
|
||||||
|
self.__pk_map[entry.identifiers["pk"]] = model.pk
|
||||||
|
entry._state = BlueprintEntryState(model)
|
||||||
self.logger.debug("updated model", model=model, pk=model.pk)
|
self.logger.debug("updated model", model=model, pk=model.pk)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def validate(self) -> bool:
|
def validate(self) -> tuple[bool, list[EventDict]]:
|
||||||
"""Validate loaded flow 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 flow import validaton")
|
self.logger.debug("Starting blueprint import validation")
|
||||||
|
orig_import = deepcopy(self.__import)
|
||||||
if self.__import.version != 1:
|
if self.__import.version != 1:
|
||||||
self.logger.warning("Invalid bundle version")
|
self.logger.warning("Invalid blueprint version")
|
||||||
return False
|
return False, []
|
||||||
with transaction_rollback():
|
with (
|
||||||
|
transaction_rollback(),
|
||||||
|
capture_logs() as logs,
|
||||||
|
):
|
||||||
successful = self._apply_models()
|
successful = self._apply_models()
|
||||||
if not successful:
|
if not successful:
|
||||||
self.logger.debug("Flow validation failed")
|
self.logger.debug("blueprint validation failed")
|
||||||
return successful
|
for log in logs:
|
||||||
|
self.logger.debug(**log)
|
||||||
|
self.__import = orig_import
|
||||||
|
return successful, logs
|
5
authentik/blueprints/v1/labels.py
Normal file
5
authentik/blueprints/v1/labels.py
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
"""Blueprint labels"""
|
||||||
|
|
||||||
|
LABEL_AUTHENTIK_SYSTEM = "blueprints.goauthentik.io/system"
|
||||||
|
LABEL_AUTHENTIK_INSTANTIATE = "blueprints.goauthentik.io/instantiate"
|
||||||
|
LABEL_AUTHENTIK_GENERATED = "blueprints.goauthentik.io/generated"
|
174
authentik/blueprints/v1/tasks.py
Normal file
174
authentik/blueprints/v1/tasks.py
Normal file
@ -0,0 +1,174 @@
|
|||||||
|
"""v1 blueprints tasks"""
|
||||||
|
from dataclasses import asdict, dataclass, field
|
||||||
|
from hashlib import sha512
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from dacite import from_dict
|
||||||
|
from django.db import DatabaseError, InternalError, ProgrammingError
|
||||||
|
from django.utils.timezone import now
|
||||||
|
from django.utils.translation import gettext_lazy as _
|
||||||
|
from structlog.stdlib import get_logger
|
||||||
|
from yaml import load
|
||||||
|
from yaml.error import YAMLError
|
||||||
|
|
||||||
|
from authentik.blueprints.models import (
|
||||||
|
BlueprintInstance,
|
||||||
|
BlueprintInstanceStatus,
|
||||||
|
BlueprintRetrievalFailed,
|
||||||
|
)
|
||||||
|
from authentik.blueprints.v1.common import BlueprintLoader, BlueprintMetadata
|
||||||
|
from authentik.blueprints.v1.importer import Importer
|
||||||
|
from authentik.blueprints.v1.labels import LABEL_AUTHENTIK_INSTANTIATE
|
||||||
|
from authentik.events.monitored_tasks import (
|
||||||
|
MonitoredTask,
|
||||||
|
TaskResult,
|
||||||
|
TaskResultStatus,
|
||||||
|
prefill_task,
|
||||||
|
)
|
||||||
|
from authentik.events.utils import sanitize_dict
|
||||||
|
from authentik.lib.config import CONFIG
|
||||||
|
from authentik.root.celery import CELERY_APP
|
||||||
|
|
||||||
|
LOGGER = get_logger()
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class BlueprintFile:
|
||||||
|
"""Basic info about a blueprint file"""
|
||||||
|
|
||||||
|
path: str
|
||||||
|
version: int
|
||||||
|
hash: str
|
||||||
|
last_m: int
|
||||||
|
meta: Optional[BlueprintMetadata] = field(default=None)
|
||||||
|
|
||||||
|
|
||||||
|
@CELERY_APP.task(
|
||||||
|
throws=(DatabaseError, ProgrammingError, InternalError),
|
||||||
|
)
|
||||||
|
def blueprints_find_dict():
|
||||||
|
"""Find blueprints as `blueprints_find` does, but return a safe dict"""
|
||||||
|
blueprints = []
|
||||||
|
for blueprint in blueprints_find():
|
||||||
|
blueprints.append(sanitize_dict(asdict(blueprint)))
|
||||||
|
return blueprints
|
||||||
|
|
||||||
|
|
||||||
|
def blueprints_find():
|
||||||
|
"""Find blueprints and return valid ones"""
|
||||||
|
blueprints = []
|
||||||
|
root = Path(CONFIG.y("blueprints_dir"))
|
||||||
|
for file in root.glob("**/*.yaml"):
|
||||||
|
path = Path(file)
|
||||||
|
LOGGER.debug("found blueprint", path=str(path))
|
||||||
|
with open(path, "r", encoding="utf-8") as blueprint_file:
|
||||||
|
try:
|
||||||
|
raw_blueprint = load(blueprint_file.read(), BlueprintLoader)
|
||||||
|
except YAMLError as exc:
|
||||||
|
raw_blueprint = None
|
||||||
|
LOGGER.warning("failed to parse blueprint", exc=exc, path=str(path))
|
||||||
|
if not raw_blueprint:
|
||||||
|
continue
|
||||||
|
metadata = raw_blueprint.get("metadata", None)
|
||||||
|
version = raw_blueprint.get("version", 1)
|
||||||
|
if version != 1:
|
||||||
|
LOGGER.warning("invalid blueprint version", version=version, path=str(path))
|
||||||
|
continue
|
||||||
|
file_hash = sha512(path.read_bytes()).hexdigest()
|
||||||
|
blueprint = BlueprintFile(path.relative_to(root), version, file_hash, path.stat().st_mtime)
|
||||||
|
blueprint.meta = from_dict(BlueprintMetadata, metadata) if metadata else None
|
||||||
|
blueprints.append(blueprint)
|
||||||
|
LOGGER.info(
|
||||||
|
"parsed & loaded blueprint",
|
||||||
|
hash=file_hash,
|
||||||
|
path=str(path),
|
||||||
|
)
|
||||||
|
return blueprints
|
||||||
|
|
||||||
|
|
||||||
|
@CELERY_APP.task(
|
||||||
|
throws=(DatabaseError, ProgrammingError, InternalError), base=MonitoredTask, bind=True
|
||||||
|
)
|
||||||
|
@prefill_task
|
||||||
|
def blueprints_discover(self: MonitoredTask):
|
||||||
|
"""Find blueprints and check if they need to be created in the database"""
|
||||||
|
count = 0
|
||||||
|
for blueprint in blueprints_find():
|
||||||
|
check_blueprint_v1_file(blueprint)
|
||||||
|
count += 1
|
||||||
|
self.set_status(
|
||||||
|
TaskResult(
|
||||||
|
TaskResultStatus.SUCCESSFUL,
|
||||||
|
messages=[_("Successfully imported %(count)d files." % {"count": count})],
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def check_blueprint_v1_file(blueprint: BlueprintFile):
|
||||||
|
"""Check if blueprint should be imported"""
|
||||||
|
instance: BlueprintInstance = BlueprintInstance.objects.filter(path=blueprint.path).first()
|
||||||
|
if (
|
||||||
|
blueprint.meta
|
||||||
|
and blueprint.meta.labels.get(LABEL_AUTHENTIK_INSTANTIATE, "").lower() == "false"
|
||||||
|
):
|
||||||
|
return
|
||||||
|
if not instance:
|
||||||
|
instance = BlueprintInstance(
|
||||||
|
name=blueprint.meta.name if blueprint.meta else str(blueprint.path),
|
||||||
|
path=blueprint.path,
|
||||||
|
context={},
|
||||||
|
status=BlueprintInstanceStatus.UNKNOWN,
|
||||||
|
enabled=True,
|
||||||
|
managed_models=[],
|
||||||
|
metadata={},
|
||||||
|
)
|
||||||
|
instance.save()
|
||||||
|
if instance.last_applied_hash != blueprint.hash:
|
||||||
|
instance.metadata = asdict(blueprint.meta) if blueprint.meta else {}
|
||||||
|
instance.save()
|
||||||
|
apply_blueprint.delay(instance.pk.hex)
|
||||||
|
|
||||||
|
|
||||||
|
@CELERY_APP.task(
|
||||||
|
bind=True,
|
||||||
|
base=MonitoredTask,
|
||||||
|
)
|
||||||
|
def apply_blueprint(self: MonitoredTask, instance_pk: str):
|
||||||
|
"""Apply single blueprint"""
|
||||||
|
self.set_uid(instance_pk)
|
||||||
|
self.save_on_success = False
|
||||||
|
try:
|
||||||
|
instance: BlueprintInstance = BlueprintInstance.objects.filter(pk=instance_pk).first()
|
||||||
|
if not instance or not instance.enabled:
|
||||||
|
return
|
||||||
|
blueprint_content = instance.retrieve()
|
||||||
|
file_hash = sha512(blueprint_content.encode()).hexdigest()
|
||||||
|
importer = Importer(blueprint_content, instance.context)
|
||||||
|
valid, logs = importer.validate()
|
||||||
|
if not valid:
|
||||||
|
instance.status = BlueprintInstanceStatus.ERROR
|
||||||
|
instance.save()
|
||||||
|
self.set_status(TaskResult(TaskResultStatus.ERROR, [x["event"] for x in logs]))
|
||||||
|
return
|
||||||
|
applied = importer.apply()
|
||||||
|
if not applied:
|
||||||
|
instance.status = BlueprintInstanceStatus.ERROR
|
||||||
|
instance.save()
|
||||||
|
self.set_status(TaskResult(TaskResultStatus.ERROR, "Failed to apply"))
|
||||||
|
return
|
||||||
|
instance.status = BlueprintInstanceStatus.SUCCESSFUL
|
||||||
|
instance.last_applied_hash = file_hash
|
||||||
|
instance.last_applied = now()
|
||||||
|
instance.save()
|
||||||
|
self.set_status(TaskResult(TaskResultStatus.SUCCESSFUL))
|
||||||
|
except (
|
||||||
|
DatabaseError,
|
||||||
|
ProgrammingError,
|
||||||
|
InternalError,
|
||||||
|
IOError,
|
||||||
|
BlueprintRetrievalFailed,
|
||||||
|
) as exc:
|
||||||
|
instance.status = BlueprintInstanceStatus.ERROR
|
||||||
|
instance.save()
|
||||||
|
self.set_status(TaskResult(TaskResultStatus.ERROR).with_error(exc))
|
@ -17,6 +17,7 @@ from rest_framework.serializers import ModelSerializer
|
|||||||
from rest_framework.viewsets import ModelViewSet
|
from rest_framework.viewsets import ModelViewSet
|
||||||
from rest_framework_guardian.filters import ObjectPermissionsFilter
|
from rest_framework_guardian.filters import ObjectPermissionsFilter
|
||||||
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.decorators import permission_required
|
from authentik.api.decorators import permission_required
|
||||||
@ -25,6 +26,7 @@ from authentik.core.api.used_by import UsedByMixin
|
|||||||
from authentik.core.api.utils import FilePathSerializer, FileUploadSerializer
|
from authentik.core.api.utils import FilePathSerializer, FileUploadSerializer
|
||||||
from authentik.core.models import Application, User
|
from authentik.core.models import Application, User
|
||||||
from authentik.events.models import EventAction
|
from authentik.events.models import EventAction
|
||||||
|
from authentik.events.utils import sanitize_dict
|
||||||
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 PolicyResult
|
||||||
@ -42,7 +44,7 @@ class ApplicationSerializer(ModelSerializer):
|
|||||||
"""Application Serializer"""
|
"""Application Serializer"""
|
||||||
|
|
||||||
launch_url = SerializerMethodField()
|
launch_url = SerializerMethodField()
|
||||||
provider_obj = ProviderSerializer(source="get_provider", required=False)
|
provider_obj = ProviderSerializer(source="get_provider", required=False, read_only=True)
|
||||||
|
|
||||||
meta_icon = ReadOnlyField(source="get_meta_icon")
|
meta_icon = ReadOnlyField(source="get_meta_icon")
|
||||||
|
|
||||||
@ -61,11 +63,13 @@ class ApplicationSerializer(ModelSerializer):
|
|||||||
"provider",
|
"provider",
|
||||||
"provider_obj",
|
"provider_obj",
|
||||||
"launch_url",
|
"launch_url",
|
||||||
|
"open_in_new_tab",
|
||||||
"meta_launch_url",
|
"meta_launch_url",
|
||||||
"meta_icon",
|
"meta_icon",
|
||||||
"meta_description",
|
"meta_description",
|
||||||
"meta_publisher",
|
"meta_publisher",
|
||||||
"policy_engine_mode",
|
"policy_engine_mode",
|
||||||
|
"group",
|
||||||
]
|
]
|
||||||
extra_kwargs = {
|
extra_kwargs = {
|
||||||
"meta_icon": {"read_only": True},
|
"meta_icon": {"read_only": True},
|
||||||
@ -83,6 +87,15 @@ class ApplicationViewSet(UsedByMixin, ModelViewSet):
|
|||||||
"meta_launch_url",
|
"meta_launch_url",
|
||||||
"meta_description",
|
"meta_description",
|
||||||
"meta_publisher",
|
"meta_publisher",
|
||||||
|
"group",
|
||||||
|
]
|
||||||
|
filterset_fields = [
|
||||||
|
"name",
|
||||||
|
"slug",
|
||||||
|
"meta_launch_url",
|
||||||
|
"meta_description",
|
||||||
|
"meta_publisher",
|
||||||
|
"group",
|
||||||
]
|
]
|
||||||
lookup_field = "slug"
|
lookup_field = "slug"
|
||||||
ordering = ["name"]
|
ordering = ["name"]
|
||||||
@ -132,12 +145,19 @@ class ApplicationViewSet(UsedByMixin, ModelViewSet):
|
|||||||
return HttpResponseBadRequest("for_user must be numerical")
|
return HttpResponseBadRequest("for_user must be numerical")
|
||||||
engine = PolicyEngine(application, for_user, request)
|
engine = PolicyEngine(application, for_user, request)
|
||||||
engine.use_cache = False
|
engine.use_cache = False
|
||||||
engine.build()
|
with capture_logs() as logs:
|
||||||
result = engine.result
|
engine.build()
|
||||||
|
result = engine.result
|
||||||
response = PolicyTestResultSerializer(PolicyResult(False))
|
response = PolicyTestResultSerializer(PolicyResult(False))
|
||||||
if result.passing:
|
if result.passing:
|
||||||
response = PolicyTestResultSerializer(PolicyResult(True))
|
response = PolicyTestResultSerializer(PolicyResult(True))
|
||||||
if request.user.is_superuser:
|
if request.user.is_superuser:
|
||||||
|
log_messages = []
|
||||||
|
for log in logs:
|
||||||
|
if log.get("process", "") == "PolicyProcess":
|
||||||
|
continue
|
||||||
|
log_messages.append(sanitize_dict(log))
|
||||||
|
result.log_messages = log_messages
|
||||||
response = PolicyTestResultSerializer(result)
|
response = PolicyTestResultSerializer(result)
|
||||||
return Response(response.data)
|
return Response(response.data)
|
||||||
|
|
||||||
|
@ -1,9 +1,10 @@
|
|||||||
"""Authenticator Devices API Views"""
|
"""Authenticator Devices API Views"""
|
||||||
from django_otp import devices_for_user
|
from django_otp import device_classes, devices_for_user
|
||||||
from django_otp.models import Device
|
from django_otp.models import Device
|
||||||
from drf_spectacular.utils import extend_schema
|
from drf_spectacular.types import OpenApiTypes
|
||||||
from rest_framework.fields import CharField, IntegerField, SerializerMethodField
|
from drf_spectacular.utils import OpenApiParameter, extend_schema
|
||||||
from rest_framework.permissions import IsAuthenticated
|
from rest_framework.fields import BooleanField, CharField, IntegerField, SerializerMethodField
|
||||||
|
from rest_framework.permissions import IsAdminUser, 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.viewsets import ViewSet
|
from rest_framework.viewsets import ViewSet
|
||||||
@ -17,6 +18,7 @@ class DeviceSerializer(MetaNameSerializer):
|
|||||||
pk = IntegerField()
|
pk = IntegerField()
|
||||||
name = CharField()
|
name = CharField()
|
||||||
type = SerializerMethodField()
|
type = SerializerMethodField()
|
||||||
|
confirmed = BooleanField()
|
||||||
|
|
||||||
def get_type(self, instance: Device) -> str:
|
def get_type(self, instance: Device) -> str:
|
||||||
"""Get type of device"""
|
"""Get type of device"""
|
||||||
@ -34,3 +36,33 @@ class DeviceViewSet(ViewSet):
|
|||||||
"""Get all devices for current user"""
|
"""Get all devices for current user"""
|
||||||
devices = devices_for_user(request.user)
|
devices = devices_for_user(request.user)
|
||||||
return Response(DeviceSerializer(devices, many=True).data)
|
return Response(DeviceSerializer(devices, many=True).data)
|
||||||
|
|
||||||
|
|
||||||
|
class AdminDeviceViewSet(ViewSet):
|
||||||
|
"""Viewset for authenticator devices"""
|
||||||
|
|
||||||
|
serializer_class = DeviceSerializer
|
||||||
|
permission_classes = [IsAdminUser]
|
||||||
|
|
||||||
|
def get_devices(self, **kwargs):
|
||||||
|
"""Get all devices in all child classes"""
|
||||||
|
for model in device_classes():
|
||||||
|
device_set = model.objects.filter(**kwargs)
|
||||||
|
yield from device_set
|
||||||
|
|
||||||
|
@extend_schema(
|
||||||
|
parameters=[
|
||||||
|
OpenApiParameter(
|
||||||
|
name="user",
|
||||||
|
location=OpenApiParameter.QUERY,
|
||||||
|
type=OpenApiTypes.INT,
|
||||||
|
)
|
||||||
|
],
|
||||||
|
responses={200: DeviceSerializer(many=True)},
|
||||||
|
)
|
||||||
|
def list(self, request: Request) -> Response:
|
||||||
|
"""Get all devices for current user"""
|
||||||
|
kwargs = {}
|
||||||
|
if "user" in request.query_params:
|
||||||
|
kwargs = {"user": request.query_params["user"]}
|
||||||
|
return Response(DeviceSerializer(self.get_devices(**kwargs), many=True).data)
|
||||||
|
@ -4,7 +4,7 @@ from json import loads
|
|||||||
from django.db.models.query import QuerySet
|
from django.db.models.query import QuerySet
|
||||||
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 rest_framework.fields import CharField, JSONField
|
from rest_framework.fields import CharField, IntegerField, JSONField
|
||||||
from rest_framework.serializers import ListSerializer, ModelSerializer, ValidationError
|
from rest_framework.serializers import ListSerializer, ModelSerializer, ValidationError
|
||||||
from rest_framework.viewsets import ModelViewSet
|
from rest_framework.viewsets import ModelViewSet
|
||||||
from rest_framework_guardian.filters import ObjectPermissionsFilter
|
from rest_framework_guardian.filters import ObjectPermissionsFilter
|
||||||
@ -46,11 +46,14 @@ class GroupSerializer(ModelSerializer):
|
|||||||
)
|
)
|
||||||
parent_name = CharField(source="parent.name", read_only=True)
|
parent_name = CharField(source="parent.name", read_only=True)
|
||||||
|
|
||||||
|
num_pk = IntegerField(read_only=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
|
|
||||||
model = Group
|
model = Group
|
||||||
fields = [
|
fields = [
|
||||||
"pk",
|
"pk",
|
||||||
|
"num_pk",
|
||||||
"name",
|
"name",
|
||||||
"is_superuser",
|
"is_superuser",
|
||||||
"parent",
|
"parent",
|
||||||
@ -59,6 +62,11 @@ class GroupSerializer(ModelSerializer):
|
|||||||
"attributes",
|
"attributes",
|
||||||
"users_obj",
|
"users_obj",
|
||||||
]
|
]
|
||||||
|
extra_kwargs = {
|
||||||
|
"users": {
|
||||||
|
"default": list,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
class GroupFilter(FilterSet):
|
class GroupFilter(FilterSet):
|
||||||
|
@ -14,12 +14,12 @@ from rest_framework.serializers import ModelSerializer, SerializerMethodField
|
|||||||
from rest_framework.viewsets import GenericViewSet
|
from rest_framework.viewsets import GenericViewSet
|
||||||
|
|
||||||
from authentik.api.decorators import permission_required
|
from authentik.api.decorators import permission_required
|
||||||
|
from authentik.blueprints.api import ManagedSerializer
|
||||||
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, PassiveSerializer, TypeCreateSerializer
|
||||||
from authentik.core.expression import PropertyMappingEvaluator
|
from authentik.core.expression import PropertyMappingEvaluator
|
||||||
from authentik.core.models import PropertyMapping
|
from authentik.core.models import PropertyMapping
|
||||||
from authentik.lib.utils.reflection import all_subclasses
|
from authentik.lib.utils.reflection import all_subclasses
|
||||||
from authentik.managed.api import ManagedSerializer
|
|
||||||
from authentik.policies.api.exec import PolicyTestSerializer
|
from authentik.policies.api.exec import PolicyTestSerializer
|
||||||
|
|
||||||
|
|
||||||
|
@ -8,11 +8,11 @@ from rest_framework.decorators import action
|
|||||||
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, SerializerMethodField
|
from rest_framework.serializers import ModelSerializer, ReadOnlyField, SerializerMethodField
|
||||||
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, OwnerPermissions
|
from authentik.api.authorization import OwnerFilter, OwnerSuperuserPermissions
|
||||||
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, TypeCreateSerializer
|
||||||
from authentik.core.models import Source, UserSourceConnection
|
from authentik.core.models import Source, UserSourceConnection
|
||||||
@ -26,6 +26,7 @@ LOGGER = get_logger()
|
|||||||
class SourceSerializer(ModelSerializer, MetaNameSerializer):
|
class SourceSerializer(ModelSerializer, MetaNameSerializer):
|
||||||
"""Source Serializer"""
|
"""Source Serializer"""
|
||||||
|
|
||||||
|
managed = ReadOnlyField()
|
||||||
component = SerializerMethodField()
|
component = SerializerMethodField()
|
||||||
|
|
||||||
def get_component(self, obj: Source) -> str:
|
def get_component(self, obj: Source) -> str:
|
||||||
@ -51,6 +52,8 @@ class SourceSerializer(ModelSerializer, MetaNameSerializer):
|
|||||||
"meta_model_name",
|
"meta_model_name",
|
||||||
"policy_engine_mode",
|
"policy_engine_mode",
|
||||||
"user_matching_mode",
|
"user_matching_mode",
|
||||||
|
"managed",
|
||||||
|
"user_path_template",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@ -66,6 +69,8 @@ class SourceViewSet(
|
|||||||
queryset = Source.objects.none()
|
queryset = Source.objects.none()
|
||||||
serializer_class = SourceSerializer
|
serializer_class = SourceSerializer
|
||||||
lookup_field = "slug"
|
lookup_field = "slug"
|
||||||
|
search_fields = ["slug", "name"]
|
||||||
|
filterset_fields = ["slug", "name", "managed"]
|
||||||
|
|
||||||
def get_queryset(self): # pragma: no cover
|
def get_queryset(self): # pragma: no cover
|
||||||
return Source.objects.select_subclasses()
|
return Source.objects.select_subclasses()
|
||||||
@ -150,6 +155,6 @@ class UserSourceConnectionViewSet(
|
|||||||
|
|
||||||
queryset = UserSourceConnection.objects.all()
|
queryset = UserSourceConnection.objects.all()
|
||||||
serializer_class = UserSourceConnectionSerializer
|
serializer_class = UserSourceConnectionSerializer
|
||||||
permission_classes = [OwnerPermissions]
|
permission_classes = [OwnerSuperuserPermissions]
|
||||||
filter_backends = [OwnerFilter, DjangoFilterBackend, OrderingFilter, SearchFilter]
|
filter_backends = [OwnerFilter, DjangoFilterBackend, OrderingFilter, SearchFilter]
|
||||||
ordering = ["pk"]
|
ordering = ["pk"]
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from django_filters.rest_framework import DjangoFilterBackend
|
from django_filters.rest_framework import DjangoFilterBackend
|
||||||
from drf_spectacular.utils import OpenApiResponse, extend_schema
|
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
|
||||||
from rest_framework.decorators import action
|
from rest_framework.decorators import action
|
||||||
from rest_framework.exceptions import ValidationError
|
from rest_framework.exceptions import ValidationError
|
||||||
@ -15,18 +15,19 @@ from rest_framework.viewsets import ModelViewSet
|
|||||||
|
|
||||||
from authentik.api.authorization import OwnerSuperuserPermissions
|
from authentik.api.authorization import OwnerSuperuserPermissions
|
||||||
from authentik.api.decorators import permission_required
|
from authentik.api.decorators import permission_required
|
||||||
|
from authentik.blueprints.api import ManagedSerializer
|
||||||
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 PassiveSerializer
|
||||||
from authentik.core.models import USER_ATTRIBUTE_TOKEN_EXPIRING, Token, TokenIntents
|
from authentik.core.models import USER_ATTRIBUTE_TOKEN_EXPIRING, Token, TokenIntents
|
||||||
from authentik.events.models import Event, EventAction
|
from authentik.events.models import Event, EventAction
|
||||||
from authentik.managed.api import ManagedSerializer
|
from authentik.events.utils import model_to_dict
|
||||||
|
|
||||||
|
|
||||||
class TokenSerializer(ManagedSerializer, ModelSerializer):
|
class TokenSerializer(ManagedSerializer, ModelSerializer):
|
||||||
"""Token Serializer"""
|
"""Token Serializer"""
|
||||||
|
|
||||||
user_obj = UserSerializer(required=False, source="user")
|
user_obj = UserSerializer(required=False, source="user", read_only=True)
|
||||||
|
|
||||||
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."""
|
||||||
@ -110,10 +111,39 @@ class TokenViewSet(UsedByMixin, ModelViewSet):
|
|||||||
404: OpenApiResponse(description="Token not found or expired"),
|
404: OpenApiResponse(description="Token not found or expired"),
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
@action(detail=True, pagination_class=None, filter_backends=[])
|
@action(detail=True, pagination_class=None, filter_backends=[], methods=["GET"])
|
||||||
# pylint: disable=unused-argument
|
# pylint: disable=unused-argument
|
||||||
def view_key(self, request: Request, identifier: str) -> Response:
|
def view_key(self, request: Request, identifier: str) -> Response:
|
||||||
"""Return token key and log access"""
|
"""Return token key and log access"""
|
||||||
token: Token = self.get_object()
|
token: Token = self.get_object()
|
||||||
Event.new(EventAction.SECRET_VIEW, secret=token).from_http(request) # noqa # nosec
|
Event.new(EventAction.SECRET_VIEW, secret=token).from_http(request) # noqa # nosec
|
||||||
return Response(TokenViewSerializer({"key": token.key}).data)
|
return Response(TokenViewSerializer({"key": token.key}).data)
|
||||||
|
|
||||||
|
@permission_required("authentik_core.set_token_key")
|
||||||
|
@extend_schema(
|
||||||
|
request=inline_serializer(
|
||||||
|
"TokenSetKey",
|
||||||
|
{
|
||||||
|
"key": CharField(),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
responses={
|
||||||
|
204: OpenApiResponse(description="Successfully changed key"),
|
||||||
|
400: OpenApiResponse(description="Missing key"),
|
||||||
|
404: OpenApiResponse(description="Token not found or expired"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
@action(detail=True, pagination_class=None, filter_backends=[], methods=["POST"])
|
||||||
|
# pylint: disable=unused-argument
|
||||||
|
def set_key(self, request: Request, identifier: str) -> Response:
|
||||||
|
"""Return token key and log access"""
|
||||||
|
token: Token = self.get_object()
|
||||||
|
key = request.POST.get("key")
|
||||||
|
if not key:
|
||||||
|
return Response(status=400)
|
||||||
|
token.key = key
|
||||||
|
token.save()
|
||||||
|
Event.new(EventAction.MODEL_UPDATED, model=model_to_dict(token)).from_http(
|
||||||
|
request
|
||||||
|
) # noqa # nosec
|
||||||
|
return Response(status=204)
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
"""User API Views"""
|
"""User API Views"""
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
from json import loads
|
from json import loads
|
||||||
from typing import Optional
|
from typing import Any, Optional
|
||||||
|
|
||||||
from django.contrib.auth import update_session_auth_hash
|
from django.contrib.auth import update_session_auth_hash
|
||||||
from django.db.models.query import QuerySet
|
from django.db.models.query import QuerySet
|
||||||
@ -17,13 +17,20 @@ from django_filters.filterset import FilterSet
|
|||||||
from drf_spectacular.types import OpenApiTypes
|
from drf_spectacular.types import OpenApiTypes
|
||||||
from drf_spectacular.utils import (
|
from drf_spectacular.utils import (
|
||||||
OpenApiParameter,
|
OpenApiParameter,
|
||||||
|
OpenApiResponse,
|
||||||
extend_schema,
|
extend_schema,
|
||||||
extend_schema_field,
|
extend_schema_field,
|
||||||
inline_serializer,
|
inline_serializer,
|
||||||
)
|
)
|
||||||
from guardian.shortcuts import get_anonymous_user, get_objects_for_user
|
from guardian.shortcuts import get_anonymous_user, get_objects_for_user
|
||||||
from rest_framework.decorators import action
|
from rest_framework.decorators import action
|
||||||
from rest_framework.fields import CharField, DictField, JSONField, SerializerMethodField
|
from rest_framework.fields import (
|
||||||
|
CharField,
|
||||||
|
IntegerField,
|
||||||
|
JSONField,
|
||||||
|
ListField,
|
||||||
|
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 (
|
from rest_framework.serializers import (
|
||||||
@ -31,7 +38,6 @@ from rest_framework.serializers import (
|
|||||||
ListSerializer,
|
ListSerializer,
|
||||||
ModelSerializer,
|
ModelSerializer,
|
||||||
PrimaryKeyRelatedField,
|
PrimaryKeyRelatedField,
|
||||||
Serializer,
|
|
||||||
ValidationError,
|
ValidationError,
|
||||||
)
|
)
|
||||||
from rest_framework.viewsets import ModelViewSet
|
from rest_framework.viewsets import ModelViewSet
|
||||||
@ -43,16 +49,23 @@ from authentik.api.decorators import permission_required
|
|||||||
from authentik.core.api.groups import GroupSerializer
|
from authentik.core.api.groups import GroupSerializer
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.utils import LinkSerializer, PassiveSerializer, is_dict
|
from authentik.core.api.utils import LinkSerializer, PassiveSerializer, is_dict
|
||||||
from authentik.core.middleware import SESSION_IMPERSONATE_ORIGINAL_USER, SESSION_IMPERSONATE_USER
|
from authentik.core.middleware import (
|
||||||
|
SESSION_KEY_IMPERSONATE_ORIGINAL_USER,
|
||||||
|
SESSION_KEY_IMPERSONATE_USER,
|
||||||
|
)
|
||||||
from authentik.core.models import (
|
from authentik.core.models import (
|
||||||
USER_ATTRIBUTE_SA,
|
USER_ATTRIBUTE_SA,
|
||||||
USER_ATTRIBUTE_TOKEN_EXPIRING,
|
USER_ATTRIBUTE_TOKEN_EXPIRING,
|
||||||
|
USER_PATH_SERVICE_ACCOUNT,
|
||||||
Group,
|
Group,
|
||||||
Token,
|
Token,
|
||||||
TokenIntents,
|
TokenIntents,
|
||||||
User,
|
User,
|
||||||
)
|
)
|
||||||
from authentik.events.models import EventAction
|
from authentik.events.models import EventAction
|
||||||
|
from authentik.flows.models import FlowToken
|
||||||
|
from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER, FlowPlanner
|
||||||
|
from authentik.flows.views.executor import QS_KEY_TOKEN
|
||||||
from authentik.stages.email.models import EmailStage
|
from authentik.stages.email.models import EmailStage
|
||||||
from authentik.stages.email.tasks import send_mails
|
from authentik.stages.email.tasks import send_mails
|
||||||
from authentik.stages.email.utils import TemplateEmailMessage
|
from authentik.stages.email.utils import TemplateEmailMessage
|
||||||
@ -72,6 +85,16 @@ class UserSerializer(ModelSerializer):
|
|||||||
)
|
)
|
||||||
groups_obj = ListSerializer(child=GroupSerializer(), read_only=True, source="ak_groups")
|
groups_obj = ListSerializer(child=GroupSerializer(), read_only=True, source="ak_groups")
|
||||||
uid = CharField(read_only=True)
|
uid = CharField(read_only=True)
|
||||||
|
username = CharField(max_length=150)
|
||||||
|
|
||||||
|
def validate_path(self, path: str) -> str:
|
||||||
|
"""Validate path"""
|
||||||
|
if path[:1] == "/" or path[-1] == "/":
|
||||||
|
raise ValidationError(_("No leading or trailing slashes allowed."))
|
||||||
|
for segment in path.split("/"):
|
||||||
|
if segment == "":
|
||||||
|
raise ValidationError(_("No empty segments in user path allowed."))
|
||||||
|
return path
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
|
|
||||||
@ -89,6 +112,7 @@ class UserSerializer(ModelSerializer):
|
|||||||
"avatar",
|
"avatar",
|
||||||
"attributes",
|
"attributes",
|
||||||
"uid",
|
"uid",
|
||||||
|
"path",
|
||||||
]
|
]
|
||||||
extra_kwargs = {
|
extra_kwargs = {
|
||||||
"name": {"allow_blank": True},
|
"name": {"allow_blank": True},
|
||||||
@ -96,14 +120,13 @@ class UserSerializer(ModelSerializer):
|
|||||||
|
|
||||||
|
|
||||||
class UserSelfSerializer(ModelSerializer):
|
class UserSelfSerializer(ModelSerializer):
|
||||||
"""User Serializer for information a user can retrieve about themselves and
|
"""User Serializer for information a user can retrieve about themselves"""
|
||||||
update about themselves"""
|
|
||||||
|
|
||||||
is_superuser = BooleanField(read_only=True)
|
is_superuser = BooleanField(read_only=True)
|
||||||
avatar = CharField(read_only=True)
|
avatar = CharField(read_only=True)
|
||||||
groups = SerializerMethodField()
|
groups = SerializerMethodField()
|
||||||
uid = CharField(read_only=True)
|
uid = CharField(read_only=True)
|
||||||
settings = DictField(source="attributes.settings", default=dict)
|
settings = SerializerMethodField()
|
||||||
|
|
||||||
@extend_schema_field(
|
@extend_schema_field(
|
||||||
ListSerializer(
|
ListSerializer(
|
||||||
@ -121,6 +144,10 @@ class UserSelfSerializer(ModelSerializer):
|
|||||||
"pk": group.pk,
|
"pk": group.pk,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
def get_settings(self, user: User) -> dict[str, Any]:
|
||||||
|
"""Get user settings with tenant and group settings applied"""
|
||||||
|
return user.group_attributes(self._context["request"]).get("settings", {})
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
|
|
||||||
model = User
|
model = User
|
||||||
@ -201,6 +228,11 @@ class UsersFilter(FilterSet):
|
|||||||
is_superuser = BooleanFilter(field_name="ak_groups", lookup_expr="is_superuser")
|
is_superuser = BooleanFilter(field_name="ak_groups", lookup_expr="is_superuser")
|
||||||
uuid = CharFilter(field_name="uuid")
|
uuid = CharFilter(field_name="uuid")
|
||||||
|
|
||||||
|
path = CharFilter(
|
||||||
|
field_name="path",
|
||||||
|
)
|
||||||
|
path_startswith = CharFilter(field_name="path", lookup_expr="startswith")
|
||||||
|
|
||||||
groups_by_name = ModelMultipleChoiceFilter(
|
groups_by_name = ModelMultipleChoiceFilter(
|
||||||
field_name="ak_groups__name",
|
field_name="ak_groups__name",
|
||||||
to_field_name="name",
|
to_field_name="name",
|
||||||
@ -265,12 +297,23 @@ class UserViewSet(UsedByMixin, ModelViewSet):
|
|||||||
LOGGER.debug("No recovery flow set")
|
LOGGER.debug("No recovery flow set")
|
||||||
return None, None
|
return None, None
|
||||||
user: User = self.get_object()
|
user: User = self.get_object()
|
||||||
token, __ = Token.objects.get_or_create(
|
planner = FlowPlanner(flow)
|
||||||
identifier=f"{user.uid}-password-reset",
|
planner.allow_empty_flows = True
|
||||||
user=user,
|
plan = planner.plan(
|
||||||
intent=TokenIntents.INTENT_RECOVERY,
|
self.request._request,
|
||||||
|
{
|
||||||
|
PLAN_CONTEXT_PENDING_USER: user,
|
||||||
|
},
|
||||||
)
|
)
|
||||||
querystring = urlencode({"token": token.key})
|
token, __ = FlowToken.objects.update_or_create(
|
||||||
|
identifier=f"{user.uid}-password-reset",
|
||||||
|
defaults={
|
||||||
|
"user": user,
|
||||||
|
"flow": flow,
|
||||||
|
"_plan": FlowToken.pickle(plan),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
querystring = urlencode({QS_KEY_TOKEN: token.key})
|
||||||
link = self.request.build_absolute_uri(
|
link = self.request.build_absolute_uri(
|
||||||
reverse_lazy("authentik_core:if-flow", kwargs={"flow_slug": flow.slug})
|
reverse_lazy("authentik_core:if-flow", kwargs={"flow_slug": flow.slug})
|
||||||
+ f"?{querystring}"
|
+ f"?{querystring}"
|
||||||
@ -292,6 +335,9 @@ class UserViewSet(UsedByMixin, ModelViewSet):
|
|||||||
{
|
{
|
||||||
"username": CharField(required=True),
|
"username": CharField(required=True),
|
||||||
"token": CharField(required=True),
|
"token": CharField(required=True),
|
||||||
|
"user_uid": CharField(required=True),
|
||||||
|
"user_pk": IntegerField(required=True),
|
||||||
|
"group_pk": CharField(required=False),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
@ -307,19 +353,27 @@ class UserViewSet(UsedByMixin, ModelViewSet):
|
|||||||
username=username,
|
username=username,
|
||||||
name=username,
|
name=username,
|
||||||
attributes={USER_ATTRIBUTE_SA: True, USER_ATTRIBUTE_TOKEN_EXPIRING: False},
|
attributes={USER_ATTRIBUTE_SA: True, USER_ATTRIBUTE_TOKEN_EXPIRING: False},
|
||||||
|
path=USER_PATH_SERVICE_ACCOUNT,
|
||||||
)
|
)
|
||||||
|
response = {
|
||||||
|
"username": user.username,
|
||||||
|
"user_uid": user.uid,
|
||||||
|
"user_pk": user.pk,
|
||||||
|
}
|
||||||
if create_group and self.request.user.has_perm("authentik_core.add_group"):
|
if create_group and self.request.user.has_perm("authentik_core.add_group"):
|
||||||
group = Group.objects.create(
|
group = Group.objects.create(
|
||||||
name=username,
|
name=username,
|
||||||
)
|
)
|
||||||
group.users.add(user)
|
group.users.add(user)
|
||||||
|
response["group_pk"] = str(group.pk)
|
||||||
token = Token.objects.create(
|
token = Token.objects.create(
|
||||||
identifier=slugify(f"service-account-{username}-password"),
|
identifier=slugify(f"service-account-{username}-password"),
|
||||||
intent=TokenIntents.INTENT_APP_PASSWORD,
|
intent=TokenIntents.INTENT_APP_PASSWORD,
|
||||||
user=user,
|
user=user,
|
||||||
expires=now() + timedelta(days=360),
|
expires=now() + timedelta(days=360),
|
||||||
)
|
)
|
||||||
return Response({"username": user.username, "token": token.key})
|
response["token"] = token.key
|
||||||
|
return Response(response)
|
||||||
except (IntegrityError) as exc:
|
except (IntegrityError) as exc:
|
||||||
return Response(data={"non_field_errors": [str(exc)]}, status=400)
|
return Response(data={"non_field_errors": [str(exc)]}, status=400)
|
||||||
|
|
||||||
@ -328,13 +382,16 @@ class UserViewSet(UsedByMixin, ModelViewSet):
|
|||||||
# pylint: disable=invalid-name
|
# pylint: disable=invalid-name
|
||||||
def me(self, request: Request) -> Response:
|
def me(self, request: Request) -> Response:
|
||||||
"""Get information about current user"""
|
"""Get information about current user"""
|
||||||
|
context = {"request": request}
|
||||||
serializer = SessionUserSerializer(
|
serializer = SessionUserSerializer(
|
||||||
data={"user": UserSelfSerializer(instance=request.user).data}
|
data={"user": UserSelfSerializer(instance=request.user, context=context).data}
|
||||||
)
|
)
|
||||||
if SESSION_IMPERSONATE_USER in request._request.session:
|
if SESSION_KEY_IMPERSONATE_USER in request._request.session:
|
||||||
serializer.initial_data["original"] = UserSelfSerializer(
|
serializer.initial_data["original"] = UserSelfSerializer(
|
||||||
instance=request._request.session[SESSION_IMPERSONATE_ORIGINAL_USER]
|
instance=request._request.session[SESSION_KEY_IMPERSONATE_ORIGINAL_USER],
|
||||||
|
context=context,
|
||||||
).data
|
).data
|
||||||
|
self.request.session.modified = True
|
||||||
return Response(serializer.initial_data)
|
return Response(serializer.initial_data)
|
||||||
|
|
||||||
@permission_required("authentik_core.reset_user_password")
|
@permission_required("authentik_core.reset_user_password")
|
||||||
@ -346,8 +403,8 @@ class UserViewSet(UsedByMixin, ModelViewSet):
|
|||||||
},
|
},
|
||||||
),
|
),
|
||||||
responses={
|
responses={
|
||||||
204: "",
|
204: OpenApiResponse(description="Successfully changed password"),
|
||||||
400: "",
|
400: OpenApiResponse(description="Bad request"),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@action(detail=True, methods=["POST"])
|
@action(detail=True, methods=["POST"])
|
||||||
@ -361,7 +418,7 @@ class UserViewSet(UsedByMixin, ModelViewSet):
|
|||||||
except (ValidationError, IntegrityError) as exc:
|
except (ValidationError, IntegrityError) as exc:
|
||||||
LOGGER.debug("Failed to set password", exc=exc)
|
LOGGER.debug("Failed to set password", exc=exc)
|
||||||
return Response(status=400)
|
return Response(status=400)
|
||||||
if user.pk == request.user.pk and SESSION_IMPERSONATE_USER not in self.request.session:
|
if user.pk == request.user.pk and SESSION_KEY_IMPERSONATE_USER not in self.request.session:
|
||||||
LOGGER.debug("Updating session hash after password change")
|
LOGGER.debug("Updating session hash after password change")
|
||||||
update_session_auth_hash(self.request, user)
|
update_session_auth_hash(self.request, user)
|
||||||
return Response(status=204)
|
return Response(status=204)
|
||||||
@ -405,8 +462,8 @@ class UserViewSet(UsedByMixin, ModelViewSet):
|
|||||||
)
|
)
|
||||||
],
|
],
|
||||||
responses={
|
responses={
|
||||||
"204": Serializer(),
|
"204": OpenApiResponse(description="Successfully sent recover email"),
|
||||||
"404": Serializer(),
|
"404": OpenApiResponse(description="Bad request"),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@action(detail=True, pagination_class=None, filter_backends=[])
|
@action(detail=True, pagination_class=None, filter_backends=[])
|
||||||
@ -454,3 +511,32 @@ class UserViewSet(UsedByMixin, ModelViewSet):
|
|||||||
if self.request.user.has_perm("authentik_core.view_user"):
|
if self.request.user.has_perm("authentik_core.view_user"):
|
||||||
return self._filter_queryset_for_list(queryset)
|
return self._filter_queryset_for_list(queryset)
|
||||||
return super().filter_queryset(queryset)
|
return super().filter_queryset(queryset)
|
||||||
|
|
||||||
|
@extend_schema(
|
||||||
|
responses={
|
||||||
|
200: inline_serializer(
|
||||||
|
"UserPathSerializer", {"paths": ListField(child=CharField(), read_only=True)}
|
||||||
|
)
|
||||||
|
},
|
||||||
|
parameters=[
|
||||||
|
OpenApiParameter(
|
||||||
|
name="search",
|
||||||
|
location=OpenApiParameter.QUERY,
|
||||||
|
type=OpenApiTypes.STR,
|
||||||
|
)
|
||||||
|
],
|
||||||
|
)
|
||||||
|
@action(detail=False, pagination_class=None)
|
||||||
|
def paths(self, request: Request) -> Response:
|
||||||
|
"""Get all user paths"""
|
||||||
|
return Response(
|
||||||
|
data={
|
||||||
|
"paths": list(
|
||||||
|
self.filter_queryset(self.get_queryset())
|
||||||
|
.values("path")
|
||||||
|
.distinct()
|
||||||
|
.order_by("path")
|
||||||
|
.values_list("path", flat=True)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
@ -1,30 +1,37 @@
|
|||||||
"""authentik core app config"""
|
"""authentik core app config"""
|
||||||
from importlib import import_module
|
from django.conf import settings
|
||||||
|
|
||||||
from django.apps import AppConfig
|
from authentik.blueprints.manager import ManagedAppConfig
|
||||||
from django.db import ProgrammingError
|
|
||||||
|
|
||||||
from authentik.core.signals import GAUGE_MODELS
|
|
||||||
from authentik.lib.utils.reflection import get_apps
|
|
||||||
|
|
||||||
|
|
||||||
class AuthentikCoreConfig(AppConfig):
|
class AuthentikCoreConfig(ManagedAppConfig):
|
||||||
"""authentik core app config"""
|
"""authentik core app config"""
|
||||||
|
|
||||||
name = "authentik.core"
|
name = "authentik.core"
|
||||||
label = "authentik_core"
|
label = "authentik_core"
|
||||||
verbose_name = "authentik Core"
|
verbose_name = "authentik Core"
|
||||||
mountpoint = ""
|
mountpoint = ""
|
||||||
|
default = True
|
||||||
|
|
||||||
def ready(self):
|
def reconcile_load_core_signals(self):
|
||||||
import_module("authentik.core.signals")
|
"""Load core signals"""
|
||||||
import_module("authentik.core.managed")
|
self.import_module("authentik.core.signals")
|
||||||
try:
|
|
||||||
for app in get_apps():
|
def reconcile_debug_worker_hook(self):
|
||||||
for model in app.get_models():
|
"""Dispatch startup tasks inline when debugging"""
|
||||||
GAUGE_MODELS.labels(
|
if settings.DEBUG:
|
||||||
model_name=model._meta.model_name,
|
from authentik.root.celery import worker_ready_hook
|
||||||
app=model._meta.app_label,
|
|
||||||
).set(model.objects.count())
|
worker_ready_hook()
|
||||||
except ProgrammingError:
|
|
||||||
pass
|
def reconcile_source_inbuilt(self):
|
||||||
|
"""Reconcile inbuilt source"""
|
||||||
|
from authentik.core.models import Source
|
||||||
|
|
||||||
|
Source.objects.update_or_create(
|
||||||
|
defaults={
|
||||||
|
"name": "authentik Built-in",
|
||||||
|
"slug": "authentik-built-in",
|
||||||
|
},
|
||||||
|
managed="goauthentik.io/sources/inbuilt",
|
||||||
|
)
|
||||||
|
@ -49,6 +49,7 @@ class TokenBackend(InbuiltBackend):
|
|||||||
# difference between an existing and a nonexistent user (#20760).
|
# difference between an existing and a nonexistent user (#20760).
|
||||||
User().set_password(password)
|
User().set_password(password)
|
||||||
return None
|
return None
|
||||||
|
# pylint: disable=no-member
|
||||||
tokens = Token.filter_not_expired(
|
tokens = Token.filter_not_expired(
|
||||||
user=user, key=password, intent=TokenIntents.INTENT_APP_PASSWORD
|
user=user, key=password, intent=TokenIntents.INTENT_APP_PASSWORD
|
||||||
)
|
)
|
||||||
|
@ -1,16 +0,0 @@
|
|||||||
"""Core managed objects"""
|
|
||||||
from authentik.core.models import Source
|
|
||||||
from authentik.managed.manager import EnsureExists, ObjectManager
|
|
||||||
|
|
||||||
|
|
||||||
class CoreManager(ObjectManager):
|
|
||||||
"""Core managed objects"""
|
|
||||||
|
|
||||||
def reconcile(self):
|
|
||||||
return [
|
|
||||||
EnsureExists(
|
|
||||||
Source,
|
|
||||||
"goauthentik.io/sources/inbuilt",
|
|
||||||
name="authentik Built-in",
|
|
||||||
),
|
|
||||||
]
|
|
0
authentik/core/management/__init__.py
Normal file
0
authentik/core/management/__init__.py
Normal file
0
authentik/core/management/commands/__init__.py
Normal file
0
authentik/core/management/commands/__init__.py
Normal file
13
authentik/core/management/commands/bootstrap_tasks.py
Normal file
13
authentik/core/management/commands/bootstrap_tasks.py
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
"""Run bootstrap tasks"""
|
||||||
|
from django.core.management.base import BaseCommand
|
||||||
|
|
||||||
|
from authentik.root.celery import _get_startup_tasks
|
||||||
|
|
||||||
|
|
||||||
|
class Command(BaseCommand):
|
||||||
|
"""Run bootstrap tasks to ensure certain objects are created"""
|
||||||
|
|
||||||
|
def handle(self, **options):
|
||||||
|
tasks = _get_startup_tasks()
|
||||||
|
for task in tasks:
|
||||||
|
task()
|
@ -2,9 +2,10 @@
|
|||||||
from django.apps import apps
|
from django.apps import apps
|
||||||
from django.contrib.auth.management import create_permissions
|
from django.contrib.auth.management import create_permissions
|
||||||
from django.core.management.base import BaseCommand, no_translations
|
from django.core.management.base import BaseCommand, no_translations
|
||||||
|
from guardian.management import create_anonymous_user
|
||||||
|
|
||||||
|
|
||||||
class Command(BaseCommand): # pragma: no cover
|
class Command(BaseCommand):
|
||||||
"""Repair missing permissions"""
|
"""Repair missing permissions"""
|
||||||
|
|
||||||
@no_translations
|
@no_translations
|
||||||
@ -13,3 +14,4 @@ class Command(BaseCommand): # pragma: no cover
|
|||||||
for app in apps.get_app_configs():
|
for app in apps.get_app_configs():
|
||||||
self.stdout.write(f"Checking app {app.name} ({app.label})\n")
|
self.stdout.write(f"Checking app {app.name} ({app.label})\n")
|
||||||
create_permissions(app, verbosity=0)
|
create_permissions(app, verbosity=0)
|
||||||
|
create_anonymous_user(None, using="default")
|
103
authentik/core/management/commands/shell.py
Normal file
103
authentik/core/management/commands/shell.py
Normal file
@ -0,0 +1,103 @@
|
|||||||
|
"""authentik shell command"""
|
||||||
|
import code
|
||||||
|
import platform
|
||||||
|
|
||||||
|
from django.apps import apps
|
||||||
|
from django.core.management.base import BaseCommand
|
||||||
|
from django.db.models import Model
|
||||||
|
from django.db.models.signals import post_save, pre_delete
|
||||||
|
|
||||||
|
from authentik import __version__
|
||||||
|
from authentik.core.models import User
|
||||||
|
from authentik.events.middleware import IGNORED_MODELS
|
||||||
|
from authentik.events.models import Event, EventAction
|
||||||
|
from authentik.events.utils import model_to_dict
|
||||||
|
|
||||||
|
BANNER_TEXT = """### authentik shell ({authentik})
|
||||||
|
### Node {node} | Arch {arch} | Python {python} """.format(
|
||||||
|
node=platform.node(),
|
||||||
|
python=platform.python_version(),
|
||||||
|
arch=platform.machine(),
|
||||||
|
authentik=__version__,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Command(BaseCommand):
|
||||||
|
"""Start the Django shell with all authentik models already imported"""
|
||||||
|
|
||||||
|
django_models = {}
|
||||||
|
|
||||||
|
def add_arguments(self, parser):
|
||||||
|
parser.add_argument(
|
||||||
|
"-c",
|
||||||
|
"--command",
|
||||||
|
help="Python code to execute (instead of starting an interactive shell)",
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_namespace(self):
|
||||||
|
"""Prepare namespace with all models"""
|
||||||
|
namespace = {}
|
||||||
|
|
||||||
|
# Gather Django models and constants from each app
|
||||||
|
for app in apps.get_app_configs():
|
||||||
|
# Load models from each app
|
||||||
|
for model in app.get_models():
|
||||||
|
namespace[model.__name__] = model
|
||||||
|
|
||||||
|
return namespace
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
# pylint: disable=unused-argument
|
||||||
|
def post_save_handler(sender, instance: Model, created: bool, **_):
|
||||||
|
"""Signal handler for all object's post_save"""
|
||||||
|
if isinstance(instance, IGNORED_MODELS):
|
||||||
|
return
|
||||||
|
|
||||||
|
action = EventAction.MODEL_CREATED if created else EventAction.MODEL_UPDATED
|
||||||
|
Event.new(action, model=model_to_dict(instance)).set_user(
|
||||||
|
User(
|
||||||
|
username="authentik-shell",
|
||||||
|
pk=0,
|
||||||
|
email="",
|
||||||
|
)
|
||||||
|
).save()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
# pylint: disable=unused-argument
|
||||||
|
def pre_delete_handler(sender, instance: Model, **_):
|
||||||
|
"""Signal handler for all object's pre_delete"""
|
||||||
|
if isinstance(instance, IGNORED_MODELS): # pragma: no cover
|
||||||
|
return
|
||||||
|
|
||||||
|
Event.new(EventAction.MODEL_DELETED, model=model_to_dict(instance)).set_user(
|
||||||
|
User(
|
||||||
|
username="authentik-shell",
|
||||||
|
pk=0,
|
||||||
|
email="",
|
||||||
|
)
|
||||||
|
).save()
|
||||||
|
|
||||||
|
def handle(self, **options):
|
||||||
|
namespace = self.get_namespace()
|
||||||
|
|
||||||
|
post_save.connect(Command.post_save_handler)
|
||||||
|
pre_delete.connect(Command.pre_delete_handler)
|
||||||
|
|
||||||
|
# If Python code has been passed, execute it and exit.
|
||||||
|
if options["command"]:
|
||||||
|
# pylint: disable=exec-used
|
||||||
|
exec(options["command"], namespace) # nosec # noqa
|
||||||
|
return
|
||||||
|
|
||||||
|
# Try to enable tab-complete
|
||||||
|
try:
|
||||||
|
import readline
|
||||||
|
import rlcompleter
|
||||||
|
except ModuleNotFoundError:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
readline.set_completer(rlcompleter.Completer(namespace).complete)
|
||||||
|
readline.parse_and_bind("tab: complete")
|
||||||
|
|
||||||
|
# Run interactive shell
|
||||||
|
code.interact(banner=BANNER_TEXT, local=namespace)
|
@ -1,19 +1,22 @@
|
|||||||
"""authentik admin Middleware to impersonate users"""
|
"""authentik admin Middleware to impersonate users"""
|
||||||
from logging import Logger
|
from contextvars import ContextVar
|
||||||
from threading import local
|
|
||||||
from typing import Callable
|
from typing import Callable
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
from django.http import HttpRequest, HttpResponse
|
from django.http import HttpRequest, HttpResponse
|
||||||
from sentry_sdk.api import set_tag
|
from sentry_sdk.api import set_tag
|
||||||
|
from structlog.contextvars import STRUCTLOG_KEY_PREFIX
|
||||||
|
|
||||||
SESSION_IMPERSONATE_USER = "authentik_impersonate_user"
|
SESSION_KEY_IMPERSONATE_USER = "authentik/impersonate/user"
|
||||||
SESSION_IMPERSONATE_ORIGINAL_USER = "authentik_impersonate_original_user"
|
SESSION_KEY_IMPERSONATE_ORIGINAL_USER = "authentik/impersonate/original_user"
|
||||||
LOCAL = local()
|
|
||||||
RESPONSE_HEADER_ID = "X-authentik-id"
|
RESPONSE_HEADER_ID = "X-authentik-id"
|
||||||
KEY_AUTH_VIA = "auth_via"
|
KEY_AUTH_VIA = "auth_via"
|
||||||
KEY_USER = "user"
|
KEY_USER = "user"
|
||||||
|
|
||||||
|
CTX_REQUEST_ID = ContextVar(STRUCTLOG_KEY_PREFIX + "request_id", default=None)
|
||||||
|
CTX_HOST = ContextVar(STRUCTLOG_KEY_PREFIX + "host", default=None)
|
||||||
|
CTX_AUTH_VIA = ContextVar(STRUCTLOG_KEY_PREFIX + KEY_AUTH_VIA, default=None)
|
||||||
|
|
||||||
|
|
||||||
class ImpersonateMiddleware:
|
class ImpersonateMiddleware:
|
||||||
"""Middleware to impersonate users"""
|
"""Middleware to impersonate users"""
|
||||||
@ -25,10 +28,10 @@ class ImpersonateMiddleware:
|
|||||||
|
|
||||||
def __call__(self, request: HttpRequest) -> HttpResponse:
|
def __call__(self, request: HttpRequest) -> HttpResponse:
|
||||||
# No permission checks are done here, they need to be checked before
|
# No permission checks are done here, they need to be checked before
|
||||||
# SESSION_IMPERSONATE_USER is set.
|
# SESSION_KEY_IMPERSONATE_USER is set.
|
||||||
|
|
||||||
if SESSION_IMPERSONATE_USER in request.session:
|
if SESSION_KEY_IMPERSONATE_USER in request.session:
|
||||||
request.user = request.session[SESSION_IMPERSONATE_USER]
|
request.user = request.session[SESSION_KEY_IMPERSONATE_USER]
|
||||||
# Ensure that the user is active, otherwise nothing will work
|
# Ensure that the user is active, otherwise nothing will work
|
||||||
request.user.is_active = True
|
request.user.is_active = True
|
||||||
|
|
||||||
@ -47,26 +50,20 @@ class RequestIDMiddleware:
|
|||||||
if not hasattr(request, "request_id"):
|
if not hasattr(request, "request_id"):
|
||||||
request_id = uuid4().hex
|
request_id = uuid4().hex
|
||||||
setattr(request, "request_id", request_id)
|
setattr(request, "request_id", request_id)
|
||||||
LOCAL.authentik = {
|
CTX_REQUEST_ID.set(request_id)
|
||||||
"request_id": request_id,
|
CTX_HOST.set(request.get_host())
|
||||||
"host": request.get_host(),
|
|
||||||
}
|
|
||||||
set_tag("authentik.request_id", request_id)
|
set_tag("authentik.request_id", request_id)
|
||||||
|
if hasattr(request, "user") and getattr(request.user, "is_authenticated", False):
|
||||||
|
CTX_AUTH_VIA.set("session")
|
||||||
|
else:
|
||||||
|
CTX_AUTH_VIA.set("unauthenticated")
|
||||||
|
|
||||||
response = self.get_response(request)
|
response = self.get_response(request)
|
||||||
|
|
||||||
response[RESPONSE_HEADER_ID] = request.request_id
|
response[RESPONSE_HEADER_ID] = request.request_id
|
||||||
setattr(response, "ak_context", {})
|
setattr(response, "ak_context", {})
|
||||||
response.ak_context.update(LOCAL.authentik)
|
response.ak_context["request_id"] = CTX_REQUEST_ID.get()
|
||||||
|
response.ak_context["host"] = CTX_HOST.get()
|
||||||
|
response.ak_context[KEY_AUTH_VIA] = CTX_AUTH_VIA.get()
|
||||||
response.ak_context[KEY_USER] = request.user.username
|
response.ak_context[KEY_USER] = request.user.username
|
||||||
for key in list(LOCAL.authentik.keys()):
|
|
||||||
del LOCAL.authentik[key]
|
|
||||||
return response
|
return response
|
||||||
|
|
||||||
|
|
||||||
# pylint: disable=unused-argument
|
|
||||||
def structlog_add_request_id(logger: Logger, method_name: str, event_dict: dict):
|
|
||||||
"""If threadlocal has authentik defined, add request_id to log"""
|
|
||||||
if hasattr(LOCAL, "authentik"):
|
|
||||||
event_dict.update(LOCAL.authentik)
|
|
||||||
if hasattr(LOCAL, "authentik_task"):
|
|
||||||
event_dict.update(LOCAL.authentik_task)
|
|
||||||
return event_dict
|
|
||||||
|
@ -12,18 +12,25 @@ import authentik.core.models
|
|||||||
|
|
||||||
|
|
||||||
def create_default_user(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
|
def create_default_user(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
|
||||||
# We have to use a direct import here, otherwise we get an object manager error
|
from django.contrib.auth.hashers import make_password
|
||||||
from authentik.core.models import User
|
|
||||||
|
|
||||||
|
User = apps.get_model("authentik_core", "User")
|
||||||
db_alias = schema_editor.connection.alias
|
db_alias = schema_editor.connection.alias
|
||||||
|
|
||||||
akadmin, _ = User.objects.using(db_alias).get_or_create(
|
akadmin, _ = User.objects.using(db_alias).get_or_create(
|
||||||
username="akadmin", email="root@localhost", name="authentik Default Admin"
|
username="akadmin", email="root@localhost", name="authentik Default Admin"
|
||||||
)
|
)
|
||||||
if "TF_BUILD" in environ or "AK_ADMIN_PASS" in environ or settings.TEST:
|
password = None
|
||||||
akadmin.set_password(environ.get("AK_ADMIN_PASS", "akadmin"), signal=False) # noqa # nosec
|
if "TF_BUILD" in environ or settings.TEST:
|
||||||
|
password = "akadmin" # noqa # nosec
|
||||||
|
if "AK_ADMIN_PASS" in environ:
|
||||||
|
password = environ["AK_ADMIN_PASS"]
|
||||||
|
if "AUTHENTIK_BOOTSTRAP_PASSWORD" in environ:
|
||||||
|
password = environ["AUTHENTIK_BOOTSTRAP_PASSWORD"]
|
||||||
|
if password:
|
||||||
|
akadmin.password = make_password(password)
|
||||||
else:
|
else:
|
||||||
akadmin.set_unusable_password()
|
akadmin.password = make_password(None)
|
||||||
akadmin.save()
|
akadmin.save()
|
||||||
|
|
||||||
|
|
||||||
|
@ -8,18 +8,25 @@ from django.db.backends.base.schema import BaseDatabaseSchemaEditor
|
|||||||
|
|
||||||
|
|
||||||
def create_default_user(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
|
def create_default_user(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
|
||||||
# We have to use a direct import here, otherwise we get an object manager error
|
from django.contrib.auth.hashers import make_password
|
||||||
from authentik.core.models import User
|
|
||||||
|
|
||||||
|
User = apps.get_model("authentik_core", "User")
|
||||||
db_alias = schema_editor.connection.alias
|
db_alias = schema_editor.connection.alias
|
||||||
|
|
||||||
akadmin, _ = User.objects.using(db_alias).get_or_create(
|
akadmin, _ = User.objects.using(db_alias).get_or_create(
|
||||||
username="akadmin", email="root@localhost", name="authentik Default Admin"
|
username="akadmin", email="root@localhost", name="authentik Default Admin"
|
||||||
)
|
)
|
||||||
if "TF_BUILD" in environ or "AK_ADMIN_PASS" in environ or settings.TEST:
|
password = None
|
||||||
akadmin.set_password(environ.get("AK_ADMIN_PASS", "akadmin"), signal=False) # noqa # nosec
|
if "TF_BUILD" in environ or settings.TEST:
|
||||||
|
password = "akadmin" # noqa # nosec
|
||||||
|
if "AK_ADMIN_PASS" in environ:
|
||||||
|
password = environ["AK_ADMIN_PASS"]
|
||||||
|
if "AUTHENTIK_BOOTSTRAP_PASSWORD" in environ:
|
||||||
|
password = environ["AUTHENTIK_BOOTSTRAP_PASSWORD"]
|
||||||
|
if password:
|
||||||
|
akadmin.password = make_password(password)
|
||||||
else:
|
else:
|
||||||
akadmin.set_unusable_password()
|
akadmin.password = make_password(None)
|
||||||
akadmin.save()
|
akadmin.save()
|
||||||
|
|
||||||
|
|
||||||
|
@ -36,22 +36,29 @@ def fix_duplicates(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
|
|||||||
|
|
||||||
|
|
||||||
def create_default_user_token(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
|
def create_default_user_token(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
|
||||||
# We have to use a direct import here, otherwise we get an object manager error
|
from authentik.core.models import TokenIntents
|
||||||
from authentik.core.models import Token, TokenIntents, User
|
|
||||||
|
User = apps.get_model("authentik_core", "User")
|
||||||
|
Token = apps.get_model("authentik_core", "Token")
|
||||||
|
|
||||||
db_alias = schema_editor.connection.alias
|
db_alias = schema_editor.connection.alias
|
||||||
|
|
||||||
akadmin = User.objects.using(db_alias).filter(username="akadmin")
|
akadmin = User.objects.using(db_alias).filter(username="akadmin")
|
||||||
if not akadmin.exists():
|
if not akadmin.exists():
|
||||||
return
|
return
|
||||||
if "AK_ADMIN_TOKEN" not in environ:
|
key = None
|
||||||
|
if "AK_ADMIN_TOKEN" in environ:
|
||||||
|
key = environ["AK_ADMIN_TOKEN"]
|
||||||
|
if "AUTHENTIK_BOOTSTRAP_TOKEN" in environ:
|
||||||
|
key = environ["AUTHENTIK_BOOTSTRAP_TOKEN"]
|
||||||
|
if not key:
|
||||||
return
|
return
|
||||||
Token.objects.using(db_alias).create(
|
Token.objects.using(db_alias).create(
|
||||||
identifier="authentik-boostrap-token",
|
identifier="authentik-bootstrap-token",
|
||||||
user=akadmin.first(),
|
user=akadmin.first(),
|
||||||
intent=TokenIntents.INTENT_API,
|
intent=TokenIntents.INTENT_API,
|
||||||
expiring=False,
|
expiring=False,
|
||||||
key=environ["AK_ADMIN_TOKEN"],
|
key=key,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
18
authentik/core/migrations/0019_application_group.py
Normal file
18
authentik/core/migrations/0019_application_group.py
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
# Generated by Django 4.0.3 on 2022-04-02 19:48
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
("authentik_core", "0018_auto_20210330_1345_squashed_0028_alter_token_intent"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name="application",
|
||||||
|
name="group",
|
||||||
|
field=models.TextField(blank=True, default=""),
|
||||||
|
),
|
||||||
|
]
|
@ -0,0 +1,20 @@
|
|||||||
|
# Generated by Django 4.0.5 on 2022-06-04 06:54
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
("authentik_core", "0019_application_group"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name="application",
|
||||||
|
name="open_in_new_tab",
|
||||||
|
field=models.BooleanField(
|
||||||
|
default=False, help_text="Open launch URL in a new browser tab or window."
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]
|
23
authentik/core/migrations/0021_source_user_path_user_path.py
Normal file
23
authentik/core/migrations/0021_source_user_path_user_path.py
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
# Generated by Django 4.0.5 on 2022-06-13 18:51
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
("authentik_core", "0020_application_open_in_new_tab"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name="source",
|
||||||
|
name="user_path_template",
|
||||||
|
field=models.TextField(default="goauthentik.io/sources/%(slug)s"),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name="user",
|
||||||
|
name="path",
|
||||||
|
field=models.TextField(default="users"),
|
||||||
|
),
|
||||||
|
]
|
26
authentik/core/migrations/0022_alter_group_parent.py
Normal file
26
authentik/core/migrations/0022_alter_group_parent.py
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
# Generated by Django 4.0.6 on 2022-08-05 22:01
|
||||||
|
|
||||||
|
import django.db.models.deletion
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
("authentik_core", "0021_source_user_path_user_path"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name="group",
|
||||||
|
name="parent",
|
||||||
|
field=models.ForeignKey(
|
||||||
|
blank=True,
|
||||||
|
default=None,
|
||||||
|
null=True,
|
||||||
|
on_delete=django.db.models.deletion.SET_NULL,
|
||||||
|
related_name="children",
|
||||||
|
to="authentik_core.group",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]
|
@ -7,22 +7,29 @@ from django.db.backends.base.schema import BaseDatabaseSchemaEditor
|
|||||||
|
|
||||||
|
|
||||||
def create_default_user_token(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
|
def create_default_user_token(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
|
||||||
# We have to use a direct import here, otherwise we get an object manager error
|
from authentik.core.models import TokenIntents
|
||||||
from authentik.core.models import Token, TokenIntents, User
|
|
||||||
|
User = apps.get_model("authentik_core", "User")
|
||||||
|
Token = apps.get_model("authentik_core", "Token")
|
||||||
|
|
||||||
db_alias = schema_editor.connection.alias
|
db_alias = schema_editor.connection.alias
|
||||||
|
|
||||||
akadmin = User.objects.using(db_alias).filter(username="akadmin")
|
akadmin = User.objects.using(db_alias).filter(username="akadmin")
|
||||||
if not akadmin.exists():
|
if not akadmin.exists():
|
||||||
return
|
return
|
||||||
if "AK_ADMIN_TOKEN" not in environ:
|
key = None
|
||||||
|
if "AK_ADMIN_TOKEN" in environ:
|
||||||
|
key = environ["AK_ADMIN_TOKEN"]
|
||||||
|
if "AUTHENTIK_BOOTSTRAP_TOKEN" in environ:
|
||||||
|
key = environ["AUTHENTIK_BOOTSTRAP_TOKEN"]
|
||||||
|
if not key:
|
||||||
return
|
return
|
||||||
Token.objects.using(db_alias).create(
|
Token.objects.using(db_alias).create(
|
||||||
identifier="authentik-boostrap-token",
|
identifier="authentik-bootstrap-token",
|
||||||
user=akadmin.first(),
|
user=akadmin.first(),
|
||||||
intent=TokenIntents.INTENT_API,
|
intent=TokenIntents.INTENT_API,
|
||||||
expiring=False,
|
expiring=False,
|
||||||
key=environ["AK_ADMIN_TOKEN"],
|
key=key,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@ -23,19 +23,22 @@ from model_utils.managers import InheritanceManager
|
|||||||
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.blueprints.models import ManagedModel
|
||||||
from authentik.core.exceptions import PropertyMappingExpressionException
|
from authentik.core.exceptions import PropertyMappingExpressionException
|
||||||
from authentik.core.signals import password_changed
|
from authentik.core.signals import password_changed
|
||||||
from authentik.core.types import UILoginButton, UserSettingSerializer
|
from authentik.core.types import UILoginButton, UserSettingSerializer
|
||||||
from authentik.lib.config import CONFIG
|
from authentik.lib.config import CONFIG, get_path_from_dict
|
||||||
from authentik.lib.generators import generate_id
|
from authentik.lib.generators import generate_id
|
||||||
from authentik.lib.models import CreatedUpdatedModel, DomainlessURLValidator, SerializerModel
|
from authentik.lib.models import CreatedUpdatedModel, DomainlessURLValidator, SerializerModel
|
||||||
from authentik.lib.utils.http import get_client_ip
|
from authentik.lib.utils.http import get_client_ip
|
||||||
from authentik.managed.models import ManagedModel
|
|
||||||
from authentik.policies.models import PolicyBindingModel
|
from authentik.policies.models import PolicyBindingModel
|
||||||
|
|
||||||
LOGGER = get_logger()
|
LOGGER = get_logger()
|
||||||
USER_ATTRIBUTE_DEBUG = "goauthentik.io/user/debug"
|
USER_ATTRIBUTE_DEBUG = "goauthentik.io/user/debug"
|
||||||
USER_ATTRIBUTE_SA = "goauthentik.io/user/service-account"
|
USER_ATTRIBUTE_SA = "goauthentik.io/user/service-account"
|
||||||
|
USER_ATTRIBUTE_GENERATED = "goauthentik.io/user/generated"
|
||||||
|
USER_ATTRIBUTE_EXPIRES = "goauthentik.io/user/expires"
|
||||||
|
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_CHANGE_USERNAME = "goauthentik.io/user/can-change-username"
|
USER_ATTRIBUTE_CHANGE_USERNAME = "goauthentik.io/user/can-change-username"
|
||||||
@ -43,6 +46,9 @@ 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_ATTRIBUTE_CAN_OVERRIDE_IP = "goauthentik.io/user/override-ips"
|
USER_ATTRIBUTE_CAN_OVERRIDE_IP = "goauthentik.io/user/override-ips"
|
||||||
|
|
||||||
|
USER_PATH_SYSTEM_PREFIX = "goauthentik.io"
|
||||||
|
USER_PATH_SERVICE_ACCOUNT = USER_PATH_SYSTEM_PREFIX + "/service-accounts"
|
||||||
|
|
||||||
GRAVATAR_URL = "https://secure.gravatar.com"
|
GRAVATAR_URL = "https://secure.gravatar.com"
|
||||||
DEFAULT_AVATAR = static("dist/assets/images/user_default.png")
|
DEFAULT_AVATAR = static("dist/assets/images/user_default.png")
|
||||||
|
|
||||||
@ -59,10 +65,10 @@ def default_token_key():
|
|||||||
"""Default token key"""
|
"""Default token key"""
|
||||||
# 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(128)
|
return generate_id(int(CONFIG.y("default_token_length")))
|
||||||
|
|
||||||
|
|
||||||
class Group(models.Model):
|
class Group(SerializerModel):
|
||||||
"""Custom Group model which supports a basic hierarchy"""
|
"""Custom Group model which supports a basic hierarchy"""
|
||||||
|
|
||||||
group_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
|
group_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
|
||||||
@ -76,11 +82,25 @@ class Group(models.Model):
|
|||||||
"Group",
|
"Group",
|
||||||
blank=True,
|
blank=True,
|
||||||
null=True,
|
null=True,
|
||||||
|
default=None,
|
||||||
on_delete=models.SET_NULL,
|
on_delete=models.SET_NULL,
|
||||||
related_name="children",
|
related_name="children",
|
||||||
)
|
)
|
||||||
attributes = models.JSONField(default=dict, blank=True)
|
attributes = models.JSONField(default=dict, blank=True)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def serializer(self) -> Serializer:
|
||||||
|
from authentik.core.api.groups import GroupSerializer
|
||||||
|
|
||||||
|
return GroupSerializer
|
||||||
|
|
||||||
|
@property
|
||||||
|
def num_pk(self) -> int:
|
||||||
|
"""Get a numerical, int32 ID for the group"""
|
||||||
|
# int max is 2147483647 (10 digits) so 9 is the max usable
|
||||||
|
# in the LDAP Outpost we use the last 5 chars so match here
|
||||||
|
return int(str(self.pk.int)[:5])
|
||||||
|
|
||||||
def is_member(self, user: "User") -> bool:
|
def is_member(self, user: "User") -> bool:
|
||||||
"""Recursively check if `user` is member of us, or any parent."""
|
"""Recursively check if `user` is member of us, or any parent."""
|
||||||
query = """
|
query = """
|
||||||
@ -93,7 +113,10 @@ class Group(models.Model):
|
|||||||
|
|
||||||
SELECT authentik_core_group.*, parents.relative_depth - 1
|
SELECT authentik_core_group.*, parents.relative_depth - 1
|
||||||
FROM authentik_core_group,parents
|
FROM authentik_core_group,parents
|
||||||
WHERE authentik_core_group.parent_id = parents.group_uuid
|
WHERE (
|
||||||
|
authentik_core_group.parent_id = parents.group_uuid and
|
||||||
|
parents.relative_depth > -20
|
||||||
|
)
|
||||||
)
|
)
|
||||||
SELECT group_uuid
|
SELECT group_uuid
|
||||||
FROM parents
|
FROM parents
|
||||||
@ -123,11 +146,12 @@ class UserManager(DjangoUserManager):
|
|||||||
return self._create_user(username, email, password, **extra_fields)
|
return self._create_user(username, email, password, **extra_fields)
|
||||||
|
|
||||||
|
|
||||||
class User(GuardianUserMixin, AbstractUser):
|
class User(SerializerModel, GuardianUserMixin, AbstractUser):
|
||||||
"""Custom User model to allow easier adding of user-based settings"""
|
"""Custom User model to allow easier adding of user-based settings"""
|
||||||
|
|
||||||
uuid = models.UUIDField(default=uuid4, editable=False)
|
uuid = models.UUIDField(default=uuid4, editable=False)
|
||||||
name = models.TextField(help_text=_("User's display name."))
|
name = models.TextField(help_text=_("User's display name."))
|
||||||
|
path = models.TextField(default="users")
|
||||||
|
|
||||||
sources = models.ManyToManyField("Source", through="UserSourceConnection")
|
sources = models.ManyToManyField("Source", through="UserSourceConnection")
|
||||||
ak_groups = models.ManyToManyField("Group", related_name="users")
|
ak_groups = models.ManyToManyField("Group", related_name="users")
|
||||||
@ -137,15 +161,28 @@ class User(GuardianUserMixin, AbstractUser):
|
|||||||
|
|
||||||
objects = UserManager()
|
objects = UserManager()
|
||||||
|
|
||||||
def group_attributes(self) -> dict[str, Any]:
|
@staticmethod
|
||||||
|
def default_path() -> str:
|
||||||
|
"""Get the default user path"""
|
||||||
|
return User._meta.get_field("path").default
|
||||||
|
|
||||||
|
def group_attributes(self, request: Optional[HttpRequest] = 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,
|
||||||
including the users attributes"""
|
including the users attributes"""
|
||||||
final_attributes = {}
|
final_attributes = {}
|
||||||
|
if request and hasattr(request, "tenant"):
|
||||||
|
always_merger.merge(final_attributes, request.tenant.attributes)
|
||||||
for group in self.ak_groups.all().order_by("name"):
|
for group in self.ak_groups.all().order_by("name"):
|
||||||
always_merger.merge(final_attributes, group.attributes)
|
always_merger.merge(final_attributes, group.attributes)
|
||||||
always_merger.merge(final_attributes, self.attributes)
|
always_merger.merge(final_attributes, self.attributes)
|
||||||
return final_attributes
|
return final_attributes
|
||||||
|
|
||||||
|
@property
|
||||||
|
def serializer(self) -> Serializer:
|
||||||
|
from authentik.core.api.users import UserSerializer
|
||||||
|
|
||||||
|
return UserSerializer
|
||||||
|
|
||||||
@cached_property
|
@cached_property
|
||||||
def is_superuser(self) -> bool:
|
def is_superuser(self) -> bool:
|
||||||
"""Get supseruser status based on membership in a group with superuser status"""
|
"""Get supseruser status based on membership in a group with superuser status"""
|
||||||
@ -156,11 +193,11 @@ class User(GuardianUserMixin, AbstractUser):
|
|||||||
"""superuser == staff user"""
|
"""superuser == staff user"""
|
||||||
return self.is_superuser # type: ignore
|
return self.is_superuser # type: ignore
|
||||||
|
|
||||||
def set_password(self, password, signal=True):
|
def set_password(self, raw_password, signal=True):
|
||||||
if self.pk and signal:
|
if self.pk and signal:
|
||||||
password_changed.send(sender=self, user=self, password=password)
|
password_changed.send(sender=self, user=self, password=raw_password)
|
||||||
self.password_change_date = now()
|
self.password_change_date = now()
|
||||||
return super().set_password(password)
|
return super().set_password(raw_password)
|
||||||
|
|
||||||
def check_password(self, raw_password: str) -> bool:
|
def check_password(self, raw_password: str) -> bool:
|
||||||
"""
|
"""
|
||||||
@ -180,7 +217,7 @@ class User(GuardianUserMixin, AbstractUser):
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def uid(self) -> str:
|
def uid(self) -> str:
|
||||||
"""Generate a globall 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}-{settings.SECRET_KEY}".encode("ascii")).hexdigest()
|
return sha256(f"{self.id}-{settings.SECRET_KEY}".encode("ascii")).hexdigest()
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@ -189,6 +226,8 @@ class User(GuardianUserMixin, AbstractUser):
|
|||||||
mode: str = CONFIG.y("avatars", "none")
|
mode: str = CONFIG.y("avatars", "none")
|
||||||
if mode == "none":
|
if mode == "none":
|
||||||
return DEFAULT_AVATAR
|
return DEFAULT_AVATAR
|
||||||
|
if mode.startswith("attributes."):
|
||||||
|
return get_path_from_dict(self.attributes, mode[11:], default=DEFAULT_AVATAR)
|
||||||
# gravatar uses md5 for their URLs, so md5 can't be avoided
|
# gravatar uses md5 for their URLs, so md5 can't be avoided
|
||||||
mail_hash = md5(self.email.lower().encode("utf-8")).hexdigest() # nosec
|
mail_hash = md5(self.email.lower().encode("utf-8")).hexdigest() # nosec
|
||||||
if mode == "gravatar":
|
if mode == "gravatar":
|
||||||
@ -250,13 +289,15 @@ class Provider(SerializerModel):
|
|||||||
return self.name
|
return self.name
|
||||||
|
|
||||||
|
|
||||||
class Application(PolicyBindingModel):
|
class Application(SerializerModel, PolicyBindingModel):
|
||||||
"""Every Application which uses authentik for authentication/identification/authorization
|
"""Every Application which uses authentik for authentication/identification/authorization
|
||||||
needs an Application record. Other authentication types can subclass this Model to
|
needs an Application record. Other authentication types can subclass this Model to
|
||||||
add custom fields and other properties"""
|
add custom fields and other properties"""
|
||||||
|
|
||||||
name = models.TextField(help_text=_("Application's display Name."))
|
name = models.TextField(help_text=_("Application's display Name."))
|
||||||
slug = models.SlugField(help_text=_("Internal application name, used in URLs."), unique=True)
|
slug = models.SlugField(help_text=_("Internal application name, used in URLs."), unique=True)
|
||||||
|
group = models.TextField(blank=True, default="")
|
||||||
|
|
||||||
provider = models.OneToOneField(
|
provider = models.OneToOneField(
|
||||||
"Provider", null=True, blank=True, default=None, on_delete=models.SET_DEFAULT
|
"Provider", null=True, blank=True, default=None, on_delete=models.SET_DEFAULT
|
||||||
)
|
)
|
||||||
@ -264,6 +305,11 @@ class Application(PolicyBindingModel):
|
|||||||
meta_launch_url = models.TextField(
|
meta_launch_url = models.TextField(
|
||||||
default="", blank=True, validators=[DomainlessURLValidator()]
|
default="", blank=True, validators=[DomainlessURLValidator()]
|
||||||
)
|
)
|
||||||
|
|
||||||
|
open_in_new_tab = models.BooleanField(
|
||||||
|
default=False, help_text=_("Open launch URL in a new browser tab or window.")
|
||||||
|
)
|
||||||
|
|
||||||
# For template applications, this can be set to /static/authentik/applications/*
|
# For template applications, this can be set to /static/authentik/applications/*
|
||||||
meta_icon = models.FileField(
|
meta_icon = models.FileField(
|
||||||
upload_to="application-icons/",
|
upload_to="application-icons/",
|
||||||
@ -274,6 +320,12 @@ class Application(PolicyBindingModel):
|
|||||||
meta_description = models.TextField(default="", blank=True)
|
meta_description = models.TextField(default="", blank=True)
|
||||||
meta_publisher = models.TextField(default="", blank=True)
|
meta_publisher = models.TextField(default="", blank=True)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def serializer(self) -> Serializer:
|
||||||
|
from authentik.core.api.applications import ApplicationSerializer
|
||||||
|
|
||||||
|
return ApplicationSerializer
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def get_meta_icon(self) -> Optional[str]:
|
def get_meta_icon(self) -> Optional[str]:
|
||||||
"""Get the URL to the App Icon image. If the name is /static or starts with http
|
"""Get the URL to the App Icon image. If the name is /static or starts with http
|
||||||
@ -287,10 +339,10 @@ class Application(PolicyBindingModel):
|
|||||||
def get_launch_url(self, user: Optional["User"] = None) -> Optional[str]:
|
def get_launch_url(self, user: Optional["User"] = None) -> Optional[str]:
|
||||||
"""Get launch URL if set, otherwise attempt to get launch URL based on provider."""
|
"""Get launch URL if set, otherwise attempt to get launch URL based on provider."""
|
||||||
url = None
|
url = None
|
||||||
if self.meta_launch_url:
|
|
||||||
url = self.meta_launch_url
|
|
||||||
if provider := self.get_provider():
|
if provider := self.get_provider():
|
||||||
url = provider.launch_url
|
url = provider.launch_url
|
||||||
|
if self.meta_launch_url:
|
||||||
|
url = self.meta_launch_url
|
||||||
if user and url:
|
if user and url:
|
||||||
if isinstance(user, SimpleLazyObject):
|
if isinstance(user, SimpleLazyObject):
|
||||||
user._setup()
|
user._setup()
|
||||||
@ -354,6 +406,8 @@ class Source(ManagedModel, SerializerModel, PolicyBindingModel):
|
|||||||
name = models.TextField(help_text=_("Source's display Name."))
|
name = models.TextField(help_text=_("Source's display Name."))
|
||||||
slug = models.SlugField(help_text=_("Internal source name, used in URLs."), unique=True)
|
slug = models.SlugField(help_text=_("Internal source name, used in URLs."), unique=True)
|
||||||
|
|
||||||
|
user_path_template = models.TextField(default="goauthentik.io/sources/%(slug)s")
|
||||||
|
|
||||||
enabled = models.BooleanField(default=True)
|
enabled = models.BooleanField(default=True)
|
||||||
property_mappings = models.ManyToManyField("PropertyMapping", default=None, blank=True)
|
property_mappings = models.ManyToManyField("PropertyMapping", default=None, blank=True)
|
||||||
|
|
||||||
@ -389,6 +443,17 @@ class Source(ManagedModel, SerializerModel, PolicyBindingModel):
|
|||||||
|
|
||||||
objects = InheritanceManager()
|
objects = InheritanceManager()
|
||||||
|
|
||||||
|
def get_user_path(self) -> str:
|
||||||
|
"""Get user path, fallback to default for formatting errors"""
|
||||||
|
try:
|
||||||
|
return self.user_path_template % {
|
||||||
|
"slug": self.slug,
|
||||||
|
}
|
||||||
|
# pylint: disable=broad-except
|
||||||
|
except Exception as exc:
|
||||||
|
LOGGER.warning("Failed to template user path", exc=exc, source=self)
|
||||||
|
return User.default_path()
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def component(self) -> str:
|
def component(self) -> str:
|
||||||
"""Return component used to edit this object"""
|
"""Return component used to edit this object"""
|
||||||
@ -408,7 +473,7 @@ class Source(ManagedModel, SerializerModel, PolicyBindingModel):
|
|||||||
return self.name
|
return self.name
|
||||||
|
|
||||||
|
|
||||||
class UserSourceConnection(CreatedUpdatedModel):
|
class UserSourceConnection(SerializerModel, CreatedUpdatedModel):
|
||||||
"""Connection between User and Source."""
|
"""Connection between User and Source."""
|
||||||
|
|
||||||
user = models.ForeignKey(User, on_delete=models.CASCADE)
|
user = models.ForeignKey(User, on_delete=models.CASCADE)
|
||||||
@ -416,6 +481,11 @@ class UserSourceConnection(CreatedUpdatedModel):
|
|||||||
|
|
||||||
objects = InheritanceManager()
|
objects = InheritanceManager()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def serializer(self) -> type[Serializer]:
|
||||||
|
"""Get serializer for this model"""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
|
|
||||||
unique_together = (("user", "source"),)
|
unique_together = (("user", "source"),)
|
||||||
@ -438,8 +508,9 @@ class ExpiringModel(models.Model):
|
|||||||
def filter_not_expired(cls, **kwargs) -> QuerySet:
|
def filter_not_expired(cls, **kwargs) -> QuerySet:
|
||||||
"""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`"""
|
||||||
expired = Q(expires__lt=now(), expiring=True)
|
for obj in cls.objects.filter(**kwargs).filter(Q(expires__lt=now(), expiring=True)):
|
||||||
return cls.objects.exclude(expired).filter(**kwargs)
|
obj.delete()
|
||||||
|
return cls.objects.filter(**kwargs)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def is_expired(self) -> bool:
|
def is_expired(self) -> bool:
|
||||||
@ -469,7 +540,7 @@ class TokenIntents(models.TextChoices):
|
|||||||
INTENT_APP_PASSWORD = "app_password" # nosec
|
INTENT_APP_PASSWORD = "app_password" # nosec
|
||||||
|
|
||||||
|
|
||||||
class Token(ManagedModel, ExpiringModel):
|
class Token(SerializerModel, ManagedModel, ExpiringModel):
|
||||||
"""Token used to authenticate the User for API Access or confirm another Stage like Email."""
|
"""Token used to authenticate the User for API Access or confirm another Stage like Email."""
|
||||||
|
|
||||||
token_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
|
token_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
|
||||||
@ -481,6 +552,12 @@ class Token(ManagedModel, ExpiringModel):
|
|||||||
user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="+")
|
user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="+")
|
||||||
description = models.TextField(default="", blank=True)
|
description = models.TextField(default="", blank=True)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def serializer(self) -> type[Serializer]:
|
||||||
|
from authentik.core.api.tokens import TokenSerializer
|
||||||
|
|
||||||
|
return TokenSerializer
|
||||||
|
|
||||||
def expire_action(self, *args, **kwargs):
|
def expire_action(self, *args, **kwargs):
|
||||||
"""Handler which is called when this object is expired."""
|
"""Handler which is called when this object is expired."""
|
||||||
from authentik.events.models import Event, EventAction
|
from authentik.events.models import Event, EventAction
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
"""authentik core signals"""
|
"""authentik core signals"""
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
from django.apps import apps
|
|
||||||
from django.contrib.auth.signals import user_logged_in, user_logged_out
|
from django.contrib.auth.signals import user_logged_in, user_logged_out
|
||||||
from django.contrib.sessions.backends.cache import KEY_PREFIX
|
from django.contrib.sessions.backends.cache import KEY_PREFIX
|
||||||
from django.core.cache import cache
|
from django.core.cache import cache
|
||||||
@ -10,30 +9,16 @@ from django.db.models import Model
|
|||||||
from django.db.models.signals import post_save, pre_delete
|
from django.db.models.signals import post_save, pre_delete
|
||||||
from django.dispatch import receiver
|
from django.dispatch import receiver
|
||||||
from django.http.request import HttpRequest
|
from django.http.request import HttpRequest
|
||||||
from prometheus_client import Gauge
|
|
||||||
|
|
||||||
from authentik.root.monitoring import monitoring_set
|
|
||||||
|
|
||||||
# Arguments: user: User, password: str
|
# Arguments: user: User, password: str
|
||||||
password_changed = Signal()
|
password_changed = Signal()
|
||||||
|
# Arguments: credentials: dict[str, any], request: HttpRequest, stage: Stage
|
||||||
GAUGE_MODELS = Gauge("authentik_models", "Count of various objects", ["model_name", "app"])
|
login_failed = Signal()
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from authentik.core.models import AuthenticatedSession, User
|
from authentik.core.models import AuthenticatedSession, User
|
||||||
|
|
||||||
|
|
||||||
@receiver(monitoring_set)
|
|
||||||
# pylint: disable=unused-argument
|
|
||||||
def monitoring_set_models(sender, **kwargs):
|
|
||||||
"""set models gauges"""
|
|
||||||
for model in apps.get_models():
|
|
||||||
GAUGE_MODELS.labels(
|
|
||||||
model_name=model._meta.model_name,
|
|
||||||
app=model._meta.app_label,
|
|
||||||
).set(model.objects.count())
|
|
||||||
|
|
||||||
|
|
||||||
@receiver(post_save)
|
@receiver(post_save)
|
||||||
# pylint: disable=unused-argument
|
# pylint: disable=unused-argument
|
||||||
def post_save_application(sender: type[Model], instance, created: bool, **_):
|
def post_save_application(sender: type[Model], instance, created: bool, **_):
|
||||||
|
@ -26,11 +26,11 @@ from authentik.flows.planner import (
|
|||||||
from authentik.flows.views.executor import NEXT_ARG_NAME, SESSION_KEY_GET, SESSION_KEY_PLAN
|
from authentik.flows.views.executor import NEXT_ARG_NAME, SESSION_KEY_GET, SESSION_KEY_PLAN
|
||||||
from authentik.lib.utils.urls import redirect_with_qs
|
from authentik.lib.utils.urls import redirect_with_qs
|
||||||
from authentik.policies.denied import AccessDeniedResponse
|
from authentik.policies.denied import AccessDeniedResponse
|
||||||
from authentik.policies.types import PolicyResult
|
|
||||||
from authentik.policies.utils import delete_none_keys
|
from authentik.policies.utils import delete_none_keys
|
||||||
from authentik.stages.password import BACKEND_INBUILT
|
from authentik.stages.password import BACKEND_INBUILT
|
||||||
from authentik.stages.password.stage import PLAN_CONTEXT_AUTHENTICATION_BACKEND
|
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
|
||||||
|
|
||||||
|
|
||||||
class Action(Enum):
|
class Action(Enum):
|
||||||
@ -165,9 +165,9 @@ class SourceFlowManager:
|
|||||||
return self.handle_enroll(connection)
|
return self.handle_enroll(connection)
|
||||||
except FlowNonApplicableException as exc:
|
except FlowNonApplicableException as exc:
|
||||||
self._logger.warning("Flow non applicable", exc=exc)
|
self._logger.warning("Flow non applicable", exc=exc)
|
||||||
return self.error_handler(exc, exc.policy_result)
|
return self.error_handler(exc)
|
||||||
# Default case, assume deny
|
# Default case, assume deny
|
||||||
error = (
|
error = Exception(
|
||||||
_(
|
_(
|
||||||
(
|
(
|
||||||
"Request to authenticate with %(source)s has been denied. Please authenticate "
|
"Request to authenticate with %(source)s has been denied. Please authenticate "
|
||||||
@ -178,14 +178,13 @@ class SourceFlowManager:
|
|||||||
)
|
)
|
||||||
return self.error_handler(error)
|
return self.error_handler(error)
|
||||||
|
|
||||||
def error_handler(
|
def error_handler(self, error: Exception) -> HttpResponse:
|
||||||
self, error: Exception, policy_result: Optional[PolicyResult] = None
|
|
||||||
) -> HttpResponse:
|
|
||||||
"""Handle any errors by returning an access denied stage"""
|
"""Handle any errors by returning an access denied stage"""
|
||||||
response = AccessDeniedResponse(self.request)
|
response = AccessDeniedResponse(self.request)
|
||||||
response.error_message = str(error)
|
response.error_message = str(error)
|
||||||
if policy_result:
|
if isinstance(error, FlowNonApplicableException):
|
||||||
response.policy_result = policy_result
|
response.policy_result = error.policy_result
|
||||||
|
response.error_message = error.messages
|
||||||
return response
|
return response
|
||||||
|
|
||||||
# pylint: disable=unused-argument
|
# pylint: disable=unused-argument
|
||||||
@ -291,5 +290,6 @@ class SourceFlowManager:
|
|||||||
connection,
|
connection,
|
||||||
**{
|
**{
|
||||||
PLAN_CONTEXT_PROMPT: delete_none_keys(self.enroll_info),
|
PLAN_CONTEXT_PROMPT: delete_none_keys(self.enroll_info),
|
||||||
|
PLAN_CONTEXT_USER_PATH: self.source.get_user_path(),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
@ -1,10 +1,18 @@
|
|||||||
"""authentik core tasks"""
|
"""authentik core tasks"""
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
from django.contrib.sessions.backends.cache import KEY_PREFIX
|
from django.contrib.sessions.backends.cache import KEY_PREFIX
|
||||||
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
|
||||||
|
|
||||||
from authentik.core.models import AuthenticatedSession, ExpiringModel
|
from authentik.core.models import (
|
||||||
|
USER_ATTRIBUTE_EXPIRES,
|
||||||
|
USER_ATTRIBUTE_GENERATED,
|
||||||
|
AuthenticatedSession,
|
||||||
|
ExpiringModel,
|
||||||
|
User,
|
||||||
|
)
|
||||||
from authentik.events.monitored_tasks import (
|
from authentik.events.monitored_tasks import (
|
||||||
MonitoredTask,
|
MonitoredTask,
|
||||||
TaskResult,
|
TaskResult,
|
||||||
@ -26,9 +34,9 @@ def clean_expired_models(self: MonitoredTask):
|
|||||||
objects = (
|
objects = (
|
||||||
cls.objects.all().exclude(expiring=False).exclude(expiring=True, expires__gt=now())
|
cls.objects.all().exclude(expiring=False).exclude(expiring=True, expires__gt=now())
|
||||||
)
|
)
|
||||||
|
amount = objects.count()
|
||||||
for obj in objects:
|
for obj in objects:
|
||||||
obj.expire_action()
|
obj.expire_action()
|
||||||
amount = objects.count()
|
|
||||||
LOGGER.debug("Expired models", model=cls, amount=amount)
|
LOGGER.debug("Expired models", model=cls, amount=amount)
|
||||||
messages.append(f"Expired {amount} {cls._meta.verbose_name_plural}")
|
messages.append(f"Expired {amount} {cls._meta.verbose_name_plural}")
|
||||||
# Special case
|
# Special case
|
||||||
@ -42,3 +50,24 @@ def clean_expired_models(self: MonitoredTask):
|
|||||||
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}")
|
||||||
self.set_status(TaskResult(TaskResultStatus.SUCCESSFUL, messages))
|
self.set_status(TaskResult(TaskResultStatus.SUCCESSFUL, messages))
|
||||||
|
|
||||||
|
|
||||||
|
@CELERY_APP.task(bind=True, base=MonitoredTask)
|
||||||
|
@prefill_task
|
||||||
|
def clean_temporary_users(self: MonitoredTask):
|
||||||
|
"""Remove temporary users created by SAML Sources"""
|
||||||
|
_now = datetime.now()
|
||||||
|
messages = []
|
||||||
|
deleted_users = 0
|
||||||
|
for user in User.objects.filter(**{f"attributes__{USER_ATTRIBUTE_GENERATED}": True}):
|
||||||
|
if not user.attributes.get(USER_ATTRIBUTE_EXPIRES):
|
||||||
|
continue
|
||||||
|
delta: timedelta = _now - datetime.fromtimestamp(
|
||||||
|
user.attributes.get(USER_ATTRIBUTE_EXPIRES)
|
||||||
|
)
|
||||||
|
if delta.total_seconds() > 0:
|
||||||
|
LOGGER.debug("User is expired and will be deleted.", user=user, delta=delta)
|
||||||
|
user.delete()
|
||||||
|
deleted_users += 1
|
||||||
|
messages.append(f"Successfully deleted {deleted_users} users.")
|
||||||
|
self.set_status(TaskResult(TaskResultStatus.SUCCESSFUL, messages))
|
||||||
|
@ -7,6 +7,12 @@
|
|||||||
<script src="{% static 'dist/admin/AdminInterface.js' %}" type="module"></script>
|
<script src="{% static 'dist/admin/AdminInterface.js' %}" type="module"></script>
|
||||||
<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)">
|
||||||
|
<script>
|
||||||
|
window.authentik = {};
|
||||||
|
window.authentik.locale = "{{ tenant.default_locale }}";
|
||||||
|
window.authentik.config = JSON.parse('{{ config_json|escapejs }}');
|
||||||
|
window.authentik.tenant = JSON.parse('{{ tenant_json|escapejs }}');
|
||||||
|
</script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block body %}
|
{% block body %}
|
||||||
|
@ -5,15 +5,25 @@
|
|||||||
|
|
||||||
{% block head_before %}
|
{% block head_before %}
|
||||||
{{ block.super }}
|
{{ block.super }}
|
||||||
|
<link rel="prefetch" href="{{ flow.background_url }}" />
|
||||||
{% if flow.compatibility_mode and not inspector %}
|
{% if flow.compatibility_mode and not inspector %}
|
||||||
<script>ShadyDOM = { force: !navigator.webdriver };</script>
|
<script>ShadyDOM = { force: !navigator.webdriver };</script>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
<script>
|
||||||
|
window.authentik = {};
|
||||||
|
window.authentik.locale = "{{ tenant.default_locale }}";
|
||||||
|
window.authentik.config = JSON.parse('{{ config_json|escapejs }}');
|
||||||
|
window.authentik.tenant = JSON.parse('{{ tenant_json|escapejs }}');
|
||||||
|
window.authentik.flow = {
|
||||||
|
"layout": "{{ flow.layout }}",
|
||||||
|
};
|
||||||
|
</script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block head %}
|
{% block head %}
|
||||||
<script src="{% static 'dist/flow/FlowInterface.js' %}" type="module"></script>
|
<script src="{% static 'dist/flow/FlowInterface.js' %}" type="module"></script>
|
||||||
<style>
|
<style>
|
||||||
.pf-c-background-image::before {
|
:root {
|
||||||
--ak-flow-background: url("{{ flow.background_url }}");
|
--ak-flow-background: url("{{ flow.background_url }}");
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user