web: Clean up error handling. Prep for permission checks.
- Add clearer reporting for API and network errors.
- Tidy error checking.
- Partial type safety for events.
* refactor cleanup behavior after stage form submit
* refresh captcha on failing Identification stage
* Revert "stages/identification: check captcha after checking authentication (#13533)"
This reverts commit b7beac6795.
Including a Captcha stage in an Identification stage is partially to
prevent password spraying attacks. The reverted commit negated this
feature to fix a UX bug. After 6fde42a9170, the functionality can now be
reinstated.
---------
Co-authored-by: Simonyi Gergő <gergo@goauthentik.io>
* web: Add InvalidationFlow to Radius Provider dialogues
## What
- Bugfix: adds the InvalidationFlow to the Radius Provider dialogues
- Repairs: `{"invalidation_flow":["This field is required."]}` message, which was *not* propagated
to the Notification.
- Nitpick: Pretties `?foo=${true}` expressions: `s/\?([^=]+)=\$\{true\}/\1/`
## Note
Yes, I know I'm going to have to do more magic when we harmonize the forms, and no, I didn't add the
Property Mappings to the wizard, and yes, I know I'm going to have pain with the *new* version of
the wizard. But this is a serious bug; you can't make Radius servers with *either* of the current
dialogues at the moment.
* web/legible/disambiguate-footer-links
# What
- Replaces the "brand links" box at the bottom of FlowExecutor with a component for showing brand
links.
# Why
- Confusion arose about what "footer links" mean in any given context, and breaking this out,
labeling it "brand-links," reduces that confusion. It also isolates and reduces the testable
surface area of the Executor.
* rename
Signed-off-by: Jens Langhammer <jens@goauthentik.io>
* simplify
Signed-off-by: Jens Langhammer <jens@goauthentik.io>
---------
Signed-off-by: Jens Langhammer <jens@goauthentik.io>
Co-authored-by: Jens Langhammer <jens@goauthentik.io>
Determining the state of the caps-lock key can be tricky as we're
dependant on a user-provided input to set a value. Thus, our initial
state defaults to not display any warning until the first keystroke.
- Revise to better use lit-html.
* stages/authenticator_email: Add basic structure for stages/authenticator_email
* stages/authenticator_email: Add stages/authenticator_email django app to settings.py
* stages/authenticator_email: Fix imports due changes introduced in #12598
* stages/authenticator_email: fix linting
* stages/authenticator_email: Add tests for token verification
* Add UI structure for authenticator_email
* Add autheticator_email to AuthenticatorValidateStageForm.ts and create AuthenticatorEmailStageForm.ts
* Add serializer property to emaildevice
* Add DeviceClasses.EMAIL to DeviceClasses
* Add migration file for DeviceClasses change (added email)
* Add new schema.yml and blueprints/schema.json to refelct email authenticator
* Fix UI to show the Email Authenticator
* Add support for email templates for the email authenticator
* Add templates
* Add DeviceClasses.EMAIL option to authenticator_validate/stage.py
* Fix logic for sending emails in stage.py and use the proper class AuthenticatorEmailStage in tasks.py
* Fix token expiration display in the email templates
* Fix authenticator email stage set up
* Add template and email to api response for Authenticator Email stage
* Fix Authenticator Email stage set up form
* Use different flow if the user has an email configured or not for Authenticator Email stage UI
* Use the correct field for the token in AuthenticatorEmailStage.ts
* Fix linting and code style
* Use the correct assertions in tests
* Fix mask email helper
* Add missing cases for Email Authenticator in the UI
* Fix email sending, add _compose_email() method to EmailDevice
* Fix cosmetic changes
* Add support for email device challenge validation in validate_selected_challenge
* Fix tests
* Add from_address to email template
* Refactor tests
* Update API Schema
* Refactor AuthenticatorEmailStage UI for cleaner code
* Fix saving token_expiry in the stage configuration
* Remove debug statements
* Add email connection settings to the Email authenticator stage configuration UI
* Remove unused field activate_on_success from AuthenticatorEmailStage
* Add tests for duplicate email, token expiration and template error
* cosmetic/styling changes
* Use authentik's GroupMemberSerializer and ManagedAppConfig in api and apps for email authenticathor
* stages/authenticator_email: Fix typos, styling and unused fields
* stages/authenticator_email: remove unused field responseStatus
* stages/authenticator_email: regen migrations
* Fix linting issues
* Fix app label issue, typos, missing user field
* Add a trailing space in email_otp.txt RFC 3676 sec. 4.3
Co-authored-by: Marc 'risson' Schmitt <marc.schmitt@risson.space>
Signed-off-by: Marcelo Elizeche Landó <marce@melizeche.com>
* Move mask_email method to a helper function in authentik.lib.utils.email
* Remove unused function
* Use authentik.stages.email.tasks instead of authentik.stages.authenticator_email.tasks, delete authentik.stages.authenticator_email.tasks
* Fix use global settings not using the global setting if there's a default
* Revert "Fix use global settings not using the global setting if there's a default"
This reverts commit 3825248bb4.
* Use user email from user attributes if exists
* Show masked email in AuthenticatorValidateStageCode
* Remove unused base.html template
* Fix linting issues
* Change token_expiry from integer to TextField, use timedelta_string_validator where necessary to process the change
* Move 'use global connection settings' up in the Email Authenticator Stage Configuration
* Show expanded connections settings when 'use global settings' is not activated for better UX
* Fix migration file, add missing validator
* Fix test for no prefilled email address
* Add tests to check session management, challenge generation and challenge response validation
* fix linting
* Add default value EmailStage for stage_class in stage.email.tasks.send_mail
* Change string representation for EmailDevice to handle authentik/events/tests/test_models.py::TestModels, add tests for the new __str__ method
* Add #nosec to skip false positive in linting validation
Signed-off-by: Marcelo Elizeche Landó <marce@melizeche.com>
* Change Email Authenticator Setup Stage name for consistency with other authenticators
* Add tests to test properties and methods of EmailDevice and AuthenticatorEmailStage, add test for email tasks
* Add tests for email challenge in authenticator_validate
* Update migration to reflect new verbose name for AuthenticatorEmailStage
* Update schema.yml to reflect new verbose name for AuthenticatorEmailStage
* Add default email subject in Email Authenticator Setup Stage configuration
* Remove from_address from email template to ensure global settings use if use global settings is on
* Add flow-default-authenticator-email-setup.yaml blueprint
* Move email authenticator blueprint to the examples folder
* Update authentik/stages/authenticator_email/models.py
Signed-off-by: Jens L. <jens@beryju.org>
* Change self.user_pk to self.user_id because user_pk doesn't exists here
* Remove unused logger import
* Remove more unused logger import
* Add error handling to authentik.lib.utils.email.mask_email
* fix linting
* don't catch Exception
Signed-off-by: Jens Langhammer <jens@goauthentik.io>
* update icons
Signed-off-by: Jens Langhammer <jens@goauthentik.io>
---------
Signed-off-by: Marcelo Elizeche Landó <marce@melizeche.com>
Signed-off-by: Jens L. <jens@beryju.org>
Signed-off-by: Jens Langhammer <jens@goauthentik.io>
Co-authored-by: Marc 'risson' Schmitt <marc.schmitt@risson.space>
Co-authored-by: Jens L. <jens@beryju.org>
Co-authored-by: Jens Langhammer <jens@goauthentik.io>
* web: Add InvalidationFlow to Radius Provider dialogues
## What
- Bugfix: adds the InvalidationFlow to the Radius Provider dialogues
- Repairs: `{"invalidation_flow":["This field is required."]}` message, which was *not* propagated
to the Notification.
- Nitpick: Pretties `?foo=${true}` expressions: `s/\?([^=]+)=\$\{true\}/\1/`
## Note
Yes, I know I'm going to have to do more magic when we harmonize the forms, and no, I didn't add the
Property Mappings to the wizard, and yes, I know I'm going to have pain with the *new* version of
the wizard. But this is a serious bug; you can't make Radius servers with *either* of the current
dialogues at the moment.
* web: streamline CaptchaStage
# What
This commit:
1. Replaces the mass of `if () { if() { if() } }` with two state tables:
- One for `render()`
- One for `renderBody()`
2. Breaks each Captcha out into "interactive" and "executive" versions
3. Creates a handler table for each Captcha type
4. Replaces the `.forEach` expression with a `for` loop.
5. Move `updated` to the end of the class.
6. Make captchDocument and captchaFrame constructed-on-demand with a cache.
7. Remove a lot of `@state` handlers
8. Give IframeMessageEvent its own type.
9. Removed `this.scriptElement`
10. Replaced `window.removeEventListener` with an `AbortController()`
# Why
1. **Replacing `if` trees with a state table.** The logic of the original was really hard to follow.
With the state table, we can clearly see now that for the `render()` function, we care about the
Boolean flags `[embedded, challenged, interactive]` and have appropriate effects for each. With
`renderBody()`, we can see that we care about the Boolean flags `[hasError, challenged]`, and can
see the appropriate effects for each one.
2. (and 3.) **Breaking each Captcha clause into separate handlers.** Again, the logic was convoluted,
when what we really care about is "Does this captcha have a corresponding handler attached to
`window`, and, if so, should we run the interactive or executive version of it?" By putting all
of that into a table of `[name, challenge, execute]`, we can clearly see what's being handled
when.
4. **Replacing `foreach()` with `for()`**: [You cannot use a `forEach()` with async
expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#:~:text=does%20not%20wait%20for%20promises).
If you need asynchronous behavior in an ordered loop, `for()` is the safest way to handle it; if
you need asynchronous behavior from multiple promises, `Promise.allSettled(handlers.map())` is
the way to go.
I tried to tell if this function *meant* to run every handler it found simultaneously, or if it
meant to test them in order; I went with the second option, breaking and exiting the loop once a
handler had run successfully.
5. **Reordered the code a bit**. We're trying to evolve a pattern in our source code: styles,
properties, states, internal variables, constructor, getters & setters that are not `@property()`
or `@state()`, DOM-related lifecycle handlers, event handlers, pre-render lifecycle handlers,
renderers, and post-render lifecycle handlers. Helper methods (including subrenderers) go above
the method(s) they help.
6. **Constructing Elements on demand with a cache**. It is not guaranteed that we will actually need
either of those. Constructing them on demand with a cache is both performant and cleaner.
Likewise, I removed these from the Lit object's `state()` table, since they're constructed once
and never change over the lifetime of an instance of `ak-stage-captcha`.
9. **Remove `this.scriptElement`**: It was never referenced outside the one function where it was used.
10. **Remove `removeEventListener()`**: `AbortController()` is a bit more verbose for small event
handler collections, but it's considered much more reliable and much cleaner.
* Didn't save the extracted ListenerController.
* add captcha to identification stage
* simplify component invocations
* fail fast on `onTokenChange` default behavior
* reword docs
* rename `token` to `captcha_token` in Identification stage contexts
(In Captcha stage contexts the name `token` seems well-scoped.)
* use `nothing` instead of ``` html`` ```
* remove rendered Captcha component from document flow on Identification stages
Note: this doesn't remove the captcha itself, if interactive, only the loading
indicator.
* add invisible requirement to captcha on Identification stage
* stylize docs
* add friendlier error messages to Captcha stage
* fix tests
* make captcha error messages even friendlier
* add test case to retriable captcha
* use default
Signed-off-by: Jens Langhammer <jens@goauthentik.io>
---------
Signed-off-by: Jens Langhammer <jens@goauthentik.io>
Co-authored-by: Jens Langhammer <jens@goauthentik.io>
* authenticator_validate: autoselect last used device class
* improve usability of `AuthenticatorValidationStage`
* don't automatically offer the recovery key authenticator validation
I believe this could confuse users more than help them
* web: move mutator block into the `willUpdate` override
Removed the section of code from the renderer that updates the state of the component;
Mutating in the middle of a render is strongly discouraged. This block contains an
algorithm for determining if the selectedDeviceChallenge should be set and how; since
`selectedDeviceChallenge` is a state, we don't want to be changing it outside of those
lifecycle methods that do not trigger a rerender.
* web: move styles() to top of class, extract custom CSS to a named block.
* lint: collapse multiple early returns, missing curly brace.
* autoselect device only once even if the user only has 1 device
* make `DeviceChallenge.last_used` nullable instead of optional
* clarify button text
* fix typo
* add docs for automatic device selection
* update docs
Co-authored-by: Tana M Berry <tanamarieberry@yahoo.com>
Signed-off-by: Simonyi Gergő <28359278+gergosimonyi@users.noreply.github.com>
* fix punctuation
---------
Signed-off-by: Simonyi Gergő <28359278+gergosimonyi@users.noreply.github.com>
Co-authored-by: Ken Sternberg <ken@goauthentik.io>
Co-authored-by: Tana M Berry <tanamarieberry@yahoo.com>
* remove wrong help text for multi select
Signed-off-by: Jens Langhammer <jens@goauthentik.io>
* make labelling for create and and bind existing more consistent
Signed-off-by: Jens Langhammer <jens@goauthentik.io>
* fix oobe missing label
Signed-off-by: Jens Langhammer <jens@goauthentik.io>
* fix application library empty state not shown
Signed-off-by: Jens Langhammer <jens@goauthentik.io>
* fix missing formatting for title on access denied stage
Signed-off-by: Jens Langhammer <jens@goauthentik.io>
---------
Signed-off-by: Jens Langhammer <jens@goauthentik.io>
* web: fix esbuild issue with style sheets
Getting ESBuild, Lit, and Storybook to all agree on how to read and parse stylesheets is a serious
pain. This fix better identifies the value types (instances) being passed from various sources in
the repo to the three *different* kinds of style processors we're using (the native one, the
polyfill one, and whatever the heck Storybook does internally).
Falling back to using older CSS instantiating techniques one era at a time seems to do the trick.
It's ugly, but in the face of the aggressive styling we use to avoid Flashes of Unstyled Content
(FLoUC), it's the logic with which we're left.
In standard mode, the following warning appears on the console when running a Flow:
```
Autofocus processing was blocked because a document already has a focused element.
```
In compatibility mode, the following **error** appears on the console when running a Flow:
```
crawler-inject.js:1106 Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.
at initDomMutationObservers (crawler-inject.js:1106:18)
at crawler-inject.js:1114:24
at Array.forEach (<anonymous>)
at initDomMutationObservers (crawler-inject.js:1114:10)
at crawler-inject.js:1549:1
initDomMutationObservers @ crawler-inject.js:1106
(anonymous) @ crawler-inject.js:1114
initDomMutationObservers @ crawler-inject.js:1114
(anonymous) @ crawler-inject.js:1549
```
Despite this error, nothing seems to be broken and flows work as anticipated.
* web: provide `show password` on login page
Provide a `show password` icon, text, and button for the password field both in the
IdentificationStage and the PasswordStage. Essentially the same code for both, although the id of
the password field is unique to each.
Requested by Cloudflare. Seems to be a common thing anyway.
Should it be an administrative option that this facility is available? From where should I derive
that information? I suspect the answer is "a site attribute," but I'd like to get confirmation.
* web: comment doesn't need to be exposed. It's sufficient where it is .
* web: fix button rendering issues
During testing, the buttons did not change as expected. We are using pure DOM
state to control the look of the button, and avoiding using `.requestUpdate()`
to avoid losing customer input, so depending upon Lit to re-render just the
button was an error.
This commit goes old-school and updates the button's label and icon using
standard DOM features, although we do lean into Lit-html`s `render()`
function to create the DOM component for the icon.
* web: provide `show password` on login page
Provide a `show password` icon, text, and button for the password field both in the
IdentificationStage and the PasswordStage. Essentially the same code for both, although the id of
the password field is unique to each.
Provide a configuration detail server-side to allow administrator to enable or disable the 'show
password' feature. Off by default.
Requested by Cloudflare. Seems to be a common thing anyway. Making it configurable wasn't in
Cloudfare's request, but it seemed logical to add.
* ensure the tests pass; quibbling over the wording of the admin field continues.
* Removed some manually identified fluff.
* web: break out `show password`-enabled input field into its own component
Provides a `show password` field, but as a LightDOM-oriented web component. This form of
input[type="password"] is for flows only, as it has a number of specializations for understanding a
flow's validating round-trip, possible error messages within the challenge, and is left within the
LightDOM both to support compatibility issues and to avoid using `elementInterals`, which is a DOM
feature not supported by some older browsers.
Avoids having to maintain two different instances of the same logic, both for permitting 'show
password', and for handling it.
* web: update PasswordStageForm according to lit-analyzer
With lit-analyzer in the mix and functional, we're seeing new complaints about
inconsistent typing in lit objects, and this was one of them.
* Another lit-analyze error found.
* web: fix esbuild issue with style sheets
Getting ESBuild, Lit, and Storybook to all agree on how to read and parse stylesheets is a serious
pain. This fix better identifies the value types (instances) being passed from various sources in
the repo to the three *different* kinds of style processors we're using (the native one, the
polyfill one, and whatever the heck Storybook does internally).
Falling back to using older CSS instantiating techniques one era at a time seems to do the trick.
It's ugly, but in the face of the aggressive styling we use to avoid Flashes of Unstyled Content
(FLoUC), it's the logic with which we're left.
In standard mode, the following warning appears on the console when running a Flow:
```
Autofocus processing was blocked because a document already has a focused element.
```
In compatibility mode, the following **error** appears on the console when running a Flow:
```
crawler-inject.js:1106 Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.
at initDomMutationObservers (crawler-inject.js:1106:18)
at crawler-inject.js:1114:24
at Array.forEach (<anonymous>)
at initDomMutationObservers (crawler-inject.js:1114:10)
at crawler-inject.js:1549:1
initDomMutationObservers @ crawler-inject.js:1106
(anonymous) @ crawler-inject.js:1114
initDomMutationObservers @ crawler-inject.js:1114
(anonymous) @ crawler-inject.js:1549
```
Despite this error, nothing seems to be broken and flows work as anticipated.
* web: all-aboard the anti-if bus, according to tooling
This commit revises a number of bugs `eslint` has been complaining about for awhile now. This is the
lesser of two PRs that will address this issue, and in this case the two biggest problems were
inappropriate conditionals (using a `switch` for a single comparison), unnecessarily named returns,
empty returns. This brings our use of conditions in-line with the coding standards we _say_ we want
in eslintrc!
* web: better names and logic for comparing the dates of Xliff vs generated files
* Missed one.
* Fixed a redirect issue that was creating an empty file in the ./web folder
* web: fix esbuild issue with style sheets
Getting ESBuild, Lit, and Storybook to all agree on how to read and parse stylesheets is a serious
pain. This fix better identifies the value types (instances) being passed from various sources in
the repo to the three *different* kinds of style processors we're using (the native one, the
polyfill one, and whatever the heck Storybook does internally).
Falling back to using older CSS instantiating techniques one era at a time seems to do the trick.
It's ugly, but in the face of the aggressive styling we use to avoid Flashes of Unstyled Content
(FLoUC), it's the logic with which we're left.
In standard mode, the following warning appears on the console when running a Flow:
```
Autofocus processing was blocked because a document already has a focused element.
```
In compatibility mode, the following **error** appears on the console when running a Flow:
```
crawler-inject.js:1106 Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.
at initDomMutationObservers (crawler-inject.js:1106:18)
at crawler-inject.js:1114:24
at Array.forEach (<anonymous>)
at initDomMutationObservers (crawler-inject.js:1114:10)
at crawler-inject.js:1549:1
initDomMutationObservers @ crawler-inject.js:1106
(anonymous) @ crawler-inject.js:1114
initDomMutationObservers @ crawler-inject.js:1114
(anonymous) @ crawler-inject.js:1549
```
Despite this error, nothing seems to be broken and flows work as anticipated.
* web: add more linting
* A reliable test for the extra code needed in analyzer, passing shellcheck
* web: re-enable custom-element-manifest and enable component checking in Typescript
This commit includes a monkeypatch to allow custom-element-manifest (CEM) to work correctly again
despite our rich collection of mixins, reactive controllers, symbol-oriented event handlers, and the
like. With that monkeypatch in place, we can now create the CEM manifest file and then exploit it so
that IDEs and the Typescript compilation pass can tell when a component is being used incorrectly;
when the wrong types are being passed to it, or when a required attribute is not initialized.
* Added building the manifest to the build process, rather than storing it. It is not appreciably slow.
* web: the most boring PR in the universe: Add HTMLTagNameElementMap to everyhing
This commit adds HTMLTagNameElementMap entries to every web component in the front end. Activating
and associating the HTMLTagNamElementMap with its class has enabled
[LitAnalyzer](https://github.com/runem/lit-analyzer/tree/master/packages/lit-analyzer) to reveal a
*lot* of basic problems within the UI, the most popular of which is "missing import." We usually get
away with it because the object being imported was already registered with the browser elsewhere,
but it still surprises me that we haven't gotten any complaints over things like:
```
./src/flow/stages/base.ts
Missing import for <ak-form-static>
96: <ak-form-static
no-missing-import
```
Given how early and fundamental that seems to be in our code, I'd have expected to hear _something_
about it.
I have not enabled most of the possible checks because, well, there are just a ton of warnings when
I do. I'd like to get in and fix those.
Aside from this, I have also _removed_ `customElement` declarations from anything declared as an
`abstract class`. It makes no sense to try and instantiate something that cannot, by definition, be
instantiated. If the class is capable of running on its own, it's not abstract, it just needs to be
overridden in child classes. Before removing the declaration I did check to make sure no other
piece of code was even *trying* to instantiate it, and so far I have detected no failures. Those
elements were:
- elements/forms/Form.ts
- element-/wizard/WizardFormPage.ts
The one that blows my mind, though, is this:
```
src/elements/forms/ProxyForm.ts
6-@customElement("ak-proxy-form")
7:export abstract class ProxyForm extends Form<unknown> {
```
Which, despite being `abstract`, is somehow instantiable?
```
src/admin/outposts/ServiceConnectionListPage.ts: <ak-proxy-form
src/admin/providers/ProviderListPage.ts: <ak-proxy-form
src/admin/sources/SourceWizard.ts: <ak-proxy-form
src/admin/sources/SourceListPage.ts: <ak-proxy-form
src/admin/providers/ProviderWizard.ts: <ak-proxy-form type=${type.component}></ak-proxy-form>
src/admin/stages/StageListPage.ts: <ak-proxy-form
```
I've made a note to investigate.
I've started a new folder where all of my one-off tools for *how* a certain PR was run. It has a
README describing what it's for, and the first tool, `add-htmlelementtagnamemaps-to-everything`, is
its first entry. That tool is also documented internally.
``` Gilbert & Sullivan
I've got a little list,
I've got a little list,
Of all the code that would never be missed,
The duplicate code of cute-and-paste,
The weak abstractions that lead to waste,
The embedded templates-- you get the gist,
There ain't none of 'em that will ever be missed,
And that's why I've got them on my list!
```